@whoz-oss/coday-client 0.123.0 → 0.124.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/3rdpartylicenses.txt +20 -20
- package/browser/chunk-2WJFXA53.js +1 -0
- package/browser/chunk-3D3KN52V.js +1 -0
- package/browser/chunk-3JGMGRXW.js +5 -0
- package/browser/chunk-3U3QVZEU.js +2 -0
- package/browser/chunk-4VZIFCB6.js +83 -0
- package/browser/chunk-53STPEYQ.js +3 -0
- package/browser/{chunk-BYYYYB67.js → chunk-6LO3ANKL.js} +1 -1
- package/browser/chunk-7MXZXY4I.js +1 -0
- package/browser/{chunk-JBAZQRNW.js → chunk-AJOXSD6I.js} +1 -1
- package/browser/chunk-AK6F2DC7.js +5 -0
- package/browser/chunk-AQ3SEH2N.js +1 -0
- package/browser/{chunk-7XMHOWLT.js → chunk-B2FFL2F7.js} +1 -1
- package/browser/chunk-B2QA6UZX.js +9 -0
- package/browser/chunk-BRHVMM4O.js +1 -0
- package/browser/chunk-CRBPOP52.js +1 -0
- package/browser/{chunk-UGL3W65S.js → chunk-DE5MXWYR.js} +1 -1
- package/browser/{chunk-VEOXUX7X.js → chunk-DRBOHCTP.js} +3 -3
- package/browser/{chunk-IZRO2LMH.js → chunk-EPA5P2I6.js} +1 -1
- package/browser/chunk-ESGUJDS6.js +1 -0
- package/browser/chunk-EWEA7F46.js +270 -0
- package/browser/chunk-FOWPCPU3.js +2 -0
- package/browser/chunk-GAZJZBKP.js +1 -0
- package/browser/chunk-H5JE6Y2U.js +1 -0
- package/browser/chunk-H6OBD3IB.js +1 -0
- package/browser/chunk-HCG45H7O.js +2 -0
- package/browser/chunk-HSNVFCBN.js +1 -0
- package/browser/chunk-HTG2SANG.js +1 -0
- package/browser/chunk-HTRRBKXE.js +2 -0
- package/browser/chunk-I5EEQETN.js +1 -0
- package/browser/chunk-I5OT3IGD.js +1 -0
- package/browser/{chunk-JQSINAMU.js → chunk-IFXDK4GQ.js} +1 -1
- package/browser/chunk-IXD43YQI.js +2 -0
- package/browser/chunk-IZFHJAEI.js +1 -0
- package/browser/chunk-J44N4WCW.js +1 -0
- package/browser/chunk-JFRMX4TL.js +1 -0
- package/browser/chunk-JUPV65PP.js +1 -0
- package/browser/chunk-KKEITF3S.js +1 -0
- package/browser/chunk-KTPX26DH.js +2 -0
- package/browser/chunk-KYPWHL43.js +1 -0
- package/browser/chunk-MWWLTJ77.js +1 -0
- package/browser/{chunk-W4XTZNHN.js → chunk-NAQEVUOV.js} +1 -1
- package/browser/chunk-O2IJMHBE.js +2 -0
- package/browser/chunk-O3U2KGCT.js +1 -0
- package/browser/chunk-OPGZ37VP.js +1 -0
- package/browser/chunk-PWDBCAQS.js +2 -0
- package/browser/chunk-Q3YY3NFM.js +1 -0
- package/browser/{chunk-DSN23Y6D.js → chunk-QSQYSFNQ.js} +1 -1
- package/browser/chunk-QWMDAFBN.js +1 -0
- package/browser/chunk-QXZ6AR76.js +1 -0
- package/browser/chunk-SHHNG775.js +1 -0
- package/browser/chunk-SPIWOGE3.js +1 -0
- package/browser/{chunk-DWEXNFR7.js → chunk-SZNIOJIK.js} +1 -1
- package/browser/chunk-TLXAJ2J2.js +1 -0
- package/browser/chunk-TNUQQNZR.js +1 -0
- package/browser/{chunk-XNWPPTWL.js → chunk-U4662WTU.js} +1 -1
- package/browser/chunk-UDGUWWGZ.js +1 -0
- package/browser/chunk-UKAN3Y3I.js +2 -0
- package/browser/{chunk-6Z6SJ4Y2.js → chunk-UORJVNGU.js} +1 -1
- package/browser/{chunk-EH7TPIXS.js → chunk-VNCIHM33.js} +1 -1
- package/browser/{chunk-5OMZQ4OZ.js → chunk-VOCIDXAB.js} +1 -1
- package/browser/{chunk-VCDX36SM.js → chunk-WNNKQ2DH.js} +4 -4
- package/browser/chunk-WPC6XC7P.js +2 -0
- package/browser/chunk-XIQ3L6H6.js +1 -0
- package/browser/chunk-XJUBZLY2.js +1 -0
- package/browser/chunk-XQ4PJULE.js +1 -0
- package/browser/chunk-YZSDQIEK.js +7 -0
- package/browser/chunk-ZAM3WGZM.js +3 -0
- package/browser/chunk-ZL64I3EB.js +4 -0
- package/browser/index.html +2 -2
- package/browser/main-PMTICERL.js +1 -0
- package/browser/{styles-HC545BYS.css → styles-THLRUXCP.css} +1 -1
- package/package.json +1 -1
- package/browser/chunk-5NUGIKIB.js +0 -1
- package/browser/chunk-6KXNYOC4.js +0 -1
- package/browser/chunk-7QG3AKRT.js +0 -1
- package/browser/chunk-AKBSVQGQ.js +0 -1
- package/browser/chunk-AVD3CUGR.js +0 -1
- package/browser/chunk-B4OTLKPN.js +0 -1
- package/browser/chunk-CR4XXAY3.js +0 -1
- package/browser/chunk-DE3P5WR7.js +0 -1
- package/browser/chunk-GHOFO7YQ.js +0 -1
- package/browser/chunk-HAWWBYDG.js +0 -1
- package/browser/chunk-HIRSL5MY.js +0 -2
- package/browser/chunk-HK2BLNG3.js +0 -1
- package/browser/chunk-HLLG2DDM.js +0 -1
- package/browser/chunk-HVJQKHJC.js +0 -10
- package/browser/chunk-I3QA4WXI.js +0 -1
- package/browser/chunk-IYJZ4CSD.js +0 -2
- package/browser/chunk-L66AMHS4.js +0 -13
- package/browser/chunk-LEUHLZHG.js +0 -1
- package/browser/chunk-LPT4NEYN.js +0 -1
- package/browser/chunk-OGOX2BYJ.js +0 -1
- package/browser/chunk-P36TOKXO.js +0 -2
- package/browser/chunk-PDZ2DBT6.js +0 -1
- package/browser/chunk-PWW4FOUT.js +0 -1
- package/browser/chunk-Q56XXDIJ.js +0 -1
- package/browser/chunk-RHMP25CV.js +0 -2
- package/browser/chunk-RIKUGKVO.js +0 -1
- package/browser/chunk-RUEXWAWX.js +0 -5
- package/browser/chunk-VU7RWHPC.js +0 -1
- package/browser/chunk-XL52MS6C.js +0 -1
- package/browser/chunk-Y3EGCKL7.js +0 -1
- package/browser/chunk-Y73HWDY3.js +0 -1
- package/browser/chunk-ZK67B6NL.js +0 -1
- package/browser/main-RALP5G7L.js +0 -359
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import{a as Ce,b as xr,c as Si}from"./chunk-YZSDQIEK.js";import{c as Ti,d as fn,f as Lt,g as bn,k as En}from"./chunk-2WJFXA53.js";import{a as gt,b as Ko,c as ve,d as Mn}from"./chunk-ESGUJDS6.js";import{a as lr}from"./chunk-UORJVNGU.js";import{a as _n,b as vn}from"./chunk-HCG45H7O.js";import{a as ht,e as er,f as tr,g as nr,k as ir,l as or,n as rr,p as Sn,r as ar,t as sr}from"./chunk-EWEA7F46.js";import{a as fr}from"./chunk-I5OT3IGD.js";import"./chunk-MWWLTJ77.js";import{b as Uo,d as gn}from"./chunk-QWMDAFBN.js";import"./chunk-WNNKQ2DH.js";import{a as br}from"./chunk-AQ3SEH2N.js";import"./chunk-UKAN3Y3I.js";import{b as hr,d as gr}from"./chunk-ZL64I3EB.js";import{a as dr,b as pr,c as mr,g as ur}from"./chunk-ZAM3WGZM.js";import{a as cr,b as kn}from"./chunk-AJOXSD6I.js";import"./chunk-53STPEYQ.js";import{b as Jo}from"./chunk-AK6F2DC7.js";import"./chunk-DRBOHCTP.js";import"./chunk-IXD43YQI.js";import{a as J,b as he}from"./chunk-WPC6XC7P.js";import{C as Tn,c as Cn,g as yn,m as wn}from"./chunk-XJUBZLY2.js";import{b as Ye}from"./chunk-XIQ3L6H6.js";import{E as Xo,K as Qo,O as We,Q as Zo,R as xn,S as qe,i as Bo,j as jo,p as Wo,s as qo,t as Yo,z as Go}from"./chunk-B2QA6UZX.js";import{$b as Lo,B as we,Bb as E,D as sn,Db as w,Ec as hn,Fb as m,Ga as ge,Gc as Vo,Ha as Oo,Hc as wi,Ja as Io,Jb as Be,Jc as _e,Ka as p,Kb as be,Lb as xe,N as Ci,Pa as Po,Rb as fe,Rc as je,T as B,Tb as f,Ub as D,Uc as Pe,Vb as ut,Wa as P,Wb as ln,Xa as Ao,Xb as cn,Ya as Do,Yb as dn,Z as Y,Za as Ro,Zb as pn,_ as ko,_b as No,a as K,ac as Ho,b as Oe,bc as zo,ca as h,d as L,dc as Nt,ec as $o,fc as yi,g as rn,ga as C,h as oe,ha as y,i as an,jb as Ue,kc as mn,la as Mo,lb as x,m as vi,mb as _,n as To,oa as H,pa as Eo,pb as me,qb as ue,rb as k,sb as c,t as $e,ta as Ve,tb as d,tc as un,u as So,ub as A,va as Ie,vb as Rt,wb as Ft,xb as Fo,ya as mt}from"./chunk-3JGMGRXW.js";var On=class n{sanitizer=h(Pe);transform(e,t){if(!t||!e)return e;let i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(${i})`,"gi"),r=e.replace(o,"<strong>$1</strong>");return this.sanitizer.bypassSecurityTrustHtml(r)}static \u0275fac=function(t){return new(t||n)};static \u0275pipe=Ro({name:"highlight",type:n,pure:!0})};var Ya=["messageInput"],Ga=["fileInput"],Xa=(n,e)=>e.name;function Qa(n,e){n&1&&(c(0,"div",3),A(1,"span",8),f(2," Recording... Click mic to stop "),d())}function Za(n,e){if(n&1&&(c(0,"span",13),f(1),d()),n&2){let t=m().$implicit,i=m(2);p(),D(" "+(i.getParameterFormat(t)||""))}}function Ka(n,e){if(n&1){let t=E();c(0,"div",10),w("click",function(){let o=C(t).$index,r=m(2);return y(r.selectAutocompleteItemByClick(o))})("keydown.enter",function(){let o=C(t).$index,r=m(2);return y(r.selectAutocompleteItemByClick(o))})("keydown.space",function(){let o=C(t).$index,r=m(2);return y(r.selectAutocompleteItemByClick(o))})("mouseenter",function(){let o=C(t).$index,r=m(2);return y(r.selectedAutocompleteIndex=o)}),c(1,"div",11),A(2,"span",12),Nt(3,"highlight"),x(4,Za,2,1,"span",13),d(),A(5,"div",14),Nt(6,"highlight"),d()}if(n&2){let t=e.$implicit,i=e.$index,o=m(2);fe("selected",i===o.selectedAutocompleteIndex),Ue("aria-selected",i===o.selectedAutocompleteIndex),p(2),k("innerHTML",yi(3,6,o.autocompleteTrigger+t.name,o.getAutocompleteQuery()),ge),p(2),_(o.hasParameterFormat(t)?4:-1),p(),k("innerHTML",yi(6,9,t.description,o.getAutocompleteQuery()),ge)}}function Ja(n,e){if(n&1&&(c(0,"div",4),me(1,Ka,7,12,"div",9,Xa),d()),n&2){let t=m();p(),ue(t.autocompleteItems)}}function es(n,e){if(n&1){let t=E();c(0,"ds-icon-button",17),w("action",function(){C(t);let o=m(2);return y(o.onStopClick())}),d()}}function ts(n,e){if(n&1){let t=E();c(0,"ds-icon-button",18),w("action",function(){C(t);let o=m(2);return y(o.sendMessage())}),d()}if(n&2){let t=m(2);fe("hidden",t.isDisabled||!t.message.trim())("active",!!t.message.trim()&&!t.isDisabled),k("title",t.getSendButtonTooltip())("disabled",t.isDisabled||!t.message.trim())}}function ns(n,e){if(n&1){let t=E();c(0,"ds-icon-button",20),w("action",function(){C(t);let o=m(3);return y(o.triggerFileUpload())}),d(),c(1,"input",21,1),w("change",function(o){C(t);let r=m(3);return y(r.onFileInputChange(o))}),d()}if(n&2){let t=m(3);k("disabled",t.isDisabled)}}function is(n,e){if(n&1){let t=E();x(0,ns,3,1),c(1,"ds-icon-button",19),w("action",function(){C(t);let o=m(2);return y(o.toggleRecording())}),d()}if(n&2){let t=m(2);_(t.showWelcome?-1:0),p(),fe("recording",t.isRecording)("hidden",t.message.trim()),k("icon",t.isRecording?"fiber_manual_record":"mic")("title",t.isRecording?"Click to stop recording":"Click to start recording")}}function os(n,e){if(n&1&&(c(0,"div",7),x(1,es,1,0,"ds-icon-button",15),x(2,ts,1,6,"ds-icon-button",16),x(3,is,2,7),d()),n&2){let t=m();p(),_(t.isThinking?1:-1),p(),_(!t.isThinking||t.message.trim()?2:-1),p(),_(t.isThinking?-1:3)}}var ft=class n{isDisabled=!1;showWelcome=!1;isThinking=!1;isStarting=!1;isSessionInitializing=!1;isStopping=!1;filesPasted=new H;messageSubmitted=new H;voiceRecordingToggled=new H;heightChanged=new H;stopRequested=new H;textareaFocused=new H;messageInput;fileInput;message="";isRecording=!1;isFocused=!1;recognition=null;sessionHadTranscript=!1;pendingLineBreaksTimeout=null;lastProcessedResultIndex=0;useEnterToSend=!1;currentInvite="";subscriptions=[];thinkingPhrases=["Processing request...","Thinking...","Working on it..."];currentThinkingPhrase="Processing request...";thinkingPhraseIndex=0;thinkingInterval=null;autocompleteVisible=!1;autocompleteTrigger=null;autocompleteItems=[];selectedAutocompleteIndex=0;preferencesService=h(ve);codayService=h(Ce);agentApiService=h(lr);promptApiService=h(br);projectStateService=h(Ye);ngOnInit(){this.initializeVoiceInput(),this.useEnterToSend=this.preferencesService.getEnterToSend(),this.subscriptions.push(this.preferencesService.voiceLanguage$.subscribe(()=>this.updateRecognitionLanguage())),this.subscriptions.push(this.preferencesService.enterToSend$.subscribe(e=>{this.useEnterToSend=e})),this.subscribeToInviteEvents(),this.subscribeToMessageRestore()}ngAfterViewInit(){this.adjustTextareaHeight(),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),200)})}ngOnChanges(e){e.isThinking&&(e.isThinking.currentValue?this.startThinkingAnimation():(this.stopThinkingAnimation(),this.isStopping=!1,e.isThinking.previousValue&&(console.log("[CHAT-TEXTAREA] Thinking ended, scheduling focus"),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),100)})))),e.isSessionInitializing&&!e.isSessionInitializing.currentValue&&e.isSessionInitializing.previousValue&&(console.log("[CHAT-TEXTAREA] Session initialization completed, scheduling focus"),requestAnimationFrame(()=>{setTimeout(()=>this.focusTextarea(),100)})),e.isStarting&&!e.isStarting.currentValue&&e.isStarting.previousValue&&this.isThinking&&(this.thinkingPhraseIndex===0?(console.log("[CHAT-TEXTAREA] Transitioning from Starting to Thinking at index 0 - restarting animation"),this.stopThinkingAnimation(),this.startThinkingAnimation()):console.log("[CHAT-TEXTAREA] Transitioning from Starting to Thinking at index",this.thinkingPhraseIndex,"- continuing without restart"))}ngOnDestroy(){this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],this.clearPendingLineBreaks(),this.stopThinkingAnimation()}onKeyDown(e){if(this.autocompleteVisible)switch(e.key){case"ArrowDown":e.preventDefault(),this.selectedAutocompleteIndex=Math.min(this.selectedAutocompleteIndex+1,this.autocompleteItems.length-1),this.scrollSelectedItemIntoView();return;case"ArrowUp":e.preventDefault(),this.selectedAutocompleteIndex=Math.max(this.selectedAutocompleteIndex-1,0),this.scrollSelectedItemIntoView();return;case"Tab":case"Enter":if(!this.message.includes(" ")){e.preventDefault(),this.selectAutocompleteItem();return}break;case"Escape":e.preventDefault(),this.hideAutocomplete();return}e.key==="Enter"&&(this.useEnterToSend?!e.shiftKey&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),this.sendMessage(!0)):(navigator.platform.toLowerCase().includes("mac")?e.metaKey:e.ctrlKey)&&!e.shiftKey&&(e.preventDefault(),this.sendMessage(!0)))}onInput(){this.adjustTextareaHeight(),this.checkForAutocomplete()}onPaste(e){let t=e.clipboardData?.items;if(!t)return;let i=Array.from(t).filter(r=>r.kind==="file");if(!i.length)return;e.preventDefault();let o=i.reduce((r,a)=>{let l=a.getAsFile();return l?[...r,l]:r},[]);o.length&&this.filesPasted.emit(o)}triggerFileUpload(){console.log("[CHAT-TEXTAREA] Triggering file upload"),this.fileInput?.nativeElement?.click()}onFileInputChange(e){let t=e.target,i=t.files;if(!i||i.length===0){console.log("[CHAT-TEXTAREA] No files selected");return}console.log("[CHAT-TEXTAREA] Files selected:",i.length);let o=Array.from(i);this.filesPasted.emit(o),t.value=""}onDocumentClick(e){if(!this.autocompleteVisible)return;let t=e.target,i=document.querySelector(".autocomplete-popup"),o=this.messageInput?.nativeElement;i&&!i.contains(t)&&o&&!o.contains(t)&&this.hideAutocomplete()}sendMessage(e=!1){let t=this.message.trim();!this.isDisabled&&(e||t)&&(this.isRecording&&this.recognition&&(this.clearPendingLineBreaks(),this.recognition.stop()),this.messageSubmitted.emit(t),this.message="",setTimeout(()=>this.adjustTextareaHeight(),0))}onStopClick(){this.isStopping=!0,this.stopRequested.emit()}toggleRecording(){this.isRecording?this.stopRecording():this.startRecording()}initializeVoiceInput(){let e=window.SpeechRecognition??window.webkitSpeechRecognition;if(console.log("[SPEECH] speechRecognition",e),!e){console.warn("[SPEECH] Speech Recognition API not available");return}this.recognition=new e,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.maxAlternatives=1,this.recognition.lang=this.getSelectedLanguage();try{"grammars"in this.recognition&&(this.recognition.serviceURI=void 0)}catch(t){console.log("[SPEECH] Advanced speech recognition parameters not supported")}this.recognition.onresult=t=>{let i="",o=Math.max(t.resultIndex,this.lastProcessedResultIndex);for(let r=o;r<t.results.length;r++)t.results[r].isFinal&&(i+=t.results[r][0].transcript,this.lastProcessedResultIndex=r+1);if(i){let r=this.improveTranscriptPunctuation(i.trim());this.sessionHadTranscript=!0,console.log("[SPEECH] onresult ending, appending to textarea",this.isRecording),this.appendToTextarea(r)}},this.recognition.onend=()=>{console.log("[SPEECH] Recognition ended. Was recording:",this.isRecording),this.isRecording=!1,this.lastProcessedResultIndex=0,this.voiceRecordingToggled.emit(this.isRecording)},this.recognition.onerror=t=>{console.error("[SPEECH] Speech recognition error:",t.error),console.log("[SPEECH] Error details:",{error:t.error,message:t.message,timeStamp:t.timeStamp}),this.isRecording=!1,this.lastProcessedResultIndex=0,this.clearPendingLineBreaks(),this.voiceRecordingToggled.emit(this.isRecording)},this.recognition.onstart=()=>{console.log("[SPEECH] Recognition started successfully")},this.recognition.onspeechstart=()=>{console.log("[SPEECH] Speech detected")},this.recognition.onspeechend=()=>{console.log("[SPEECH] Speech ended")}}startRecording(){return L(this,null,function*(){if(!(!this.recognition||this.isRecording))try{this.isRecording=!0,this.sessionHadTranscript=!1,this.lastProcessedResultIndex=0,this.clearPendingLineBreaks(),this.voiceRecordingToggled.emit(this.isRecording),this.recognition.start(),console.log("[SPEECH] Started recording")}catch(e){console.error("[SPEECH] Failed to start recording:",e),this.isRecording=!1,this.voiceRecordingToggled.emit(this.isRecording)}})}stopRecording(){if(!this.recognition||!this.isRecording){console.log("[SPEECH] stopRecording not recording");return}try{console.log("[SPEECH] stopRecording recognition stop"),this.recognition.stop(),this.schedulePendingLineBreaks()}catch(e){console.error("[SPEECH] Failed to stop recording:",e)}}getSelectedLanguage(){return this.preferencesService.getVoiceLanguage()}updateRecognitionLanguage(){if(this.recognition){let e=this.getSelectedLanguage();this.recognition.lang=e,console.log("[SPEECH] Language changed to:",e)}}improveTranscriptPunctuation(e){let t=e;return/[.!?]$/.test(t.trim())||(t=t.trim()+"."),t=t.charAt(0).toUpperCase()+t.slice(1),t=t.replace(/\s+/g," "),t=t+" ",t}appendToTextarea(e){let t=this.message;if(this.message=t?`${t}${e}`:e,this.messageInput?.nativeElement){this.messageInput.nativeElement.focus();let i=this.message.length;this.messageInput.nativeElement.setSelectionRange(i,i)}setTimeout(()=>this.adjustTextareaHeight(),0)}schedulePendingLineBreaks(){this.clearPendingLineBreaks(),this.pendingLineBreaksTimeout=window.setTimeout(()=>{this.sessionHadTranscript&&(console.log("[SPEECH] Adding line breaks after transcript session"),this.appendToTextarea(`
|
|
2
|
+
|
|
3
|
+
`),this.sessionHadTranscript=!1),this.pendingLineBreaksTimeout=null},500)}clearPendingLineBreaks(){this.pendingLineBreaksTimeout&&(clearTimeout(this.pendingLineBreaksTimeout),this.pendingLineBreaksTimeout=null)}adjustTextareaHeight(){let e=this.messageInput?.nativeElement;if(!e)return;let t=e.parentElement?.offsetHeight??e.offsetHeight+32;this.heightChanged.emit(t)}getSendButtonShortcut(){return this.useEnterToSend?"Enter":navigator.platform.toLowerCase().includes("mac")?"\u2318+Enter":"Ctrl+Enter"}getSendButtonTooltip(){return this.useEnterToSend?"Send message (Enter) - Shift+Enter for new line":`Send message (${navigator.platform.toLowerCase().includes("mac")?"Cmd+Enter":"Ctrl+Enter"}) - Enter for new line`}getPlaceholder(){return this.isSessionInitializing?"Initializing session...":this.isThinking?this.isStopping?"Stopping...":this.isStarting?"Processing request...":this.currentThinkingPhrase:this.showWelcome?"How can I help you today?":"Type '@' for agents, '/' for commands, or just your message..."}startThinkingAnimation(){this.thinkingPhraseIndex=0,this.currentThinkingPhrase=this.thinkingPhrases[0]??"Thinking...",this.thinkingInterval=window.setInterval(()=>{this.thinkingPhraseIndex<this.thinkingPhrases.length-1&&(this.thinkingPhraseIndex++,this.currentThinkingPhrase=this.thinkingPhrases[this.thinkingPhraseIndex]??"Thinking...")},2e3)}stopThinkingAnimation(){this.thinkingInterval&&(clearInterval(this.thinkingInterval),this.thinkingInterval=null),this.thinkingPhraseIndex=0,this.currentThinkingPhrase="Thinking..."}subscribeToInviteEvents(){this.subscriptions.push(this.codayService.currentInviteEvent$.subscribe(e=>{e?this.handleInviteEvent(e.invite,e.defaultValue):this.currentInvite=""}))}handleInviteEvent(e,t){this.currentInvite=e,t&&(this.message=t,setTimeout(()=>this.adjustTextareaHeight(),0)),setTimeout(()=>{this.messageInput?.nativeElement&&this.messageInput.nativeElement.focus()},50)}subscribeToMessageRestore(){this.subscriptions.push(this.codayService.messageToRestore$.subscribe(e=>{e.trim()&&(console.log("[CHAT-TEXTAREA] Restoring message content:",e.substring(0,50)+"..."),this.restoreMessageContent(e))}))}restoreMessageContent(e){this.message=e,this.messageInput?.nativeElement&&(this.messageInput.nativeElement.focus(),setTimeout(()=>{let t=this.messageInput.nativeElement,i=this.message.length;t.setSelectionRange(i,i)},0)),setTimeout(()=>this.adjustTextareaHeight(),10)}focusTextarea(){let e=this.messageInput?.nativeElement;console.log("[CHAT-TEXTAREA] focusTextarea called",{hasElement:!!e,isDisabled:this.isDisabled,isThinking:this.isThinking,elementDisabled:e?.disabled,isSessionInitializing:this.isSessionInitializing}),e&&!e.disabled?(e.focus(),console.log("[CHAT-TEXTAREA] Textarea focused successfully")):console.log("[CHAT-TEXTAREA] Focus blocked - element disabled or not available")}checkForAutocomplete(){let e=this.message;if(e.startsWith("@")){let t=e.substring(1);if(t.includes(" ")){this.hideAutocomplete();return}this.showAgentAutocomplete(t);return}if(e.startsWith("/")){let t=e.substring(1);if(t.includes(" ")){this.hideAutocomplete();return}this.showPromptAutocomplete(t);return}this.hideAutocomplete()}showAgentAutocomplete(e){this.autocompleteTrigger="@";try{let t=this.projectStateService.getSelectedProjectIdOrThrow();this.agentApiService.getAgentsAutocomplete(t,e).subscribe({next:i=>{this.autocompleteItems=i,this.autocompleteVisible=i.length>0,this.selectedAutocompleteIndex=0},error:i=>{console.error("[AUTOCOMPLETE] Error loading agents:",i),this.hideAutocomplete()}})}catch(t){console.warn("[AUTOCOMPLETE] No project selected, cannot load agents"),this.hideAutocomplete()}}showPromptAutocomplete(e){this.autocompleteTrigger="/";try{let t=this.projectStateService.getSelectedProjectIdOrThrow();this.promptApiService.getPromptsAutocomplete(t,e).subscribe({next:i=>{this.autocompleteItems=i,this.autocompleteVisible=i.length>0,this.selectedAutocompleteIndex=0},error:i=>{console.error("[AUTOCOMPLETE] Error loading prompts:",i),this.hideAutocomplete()}})}catch(t){console.warn("[AUTOCOMPLETE] No project selected, cannot load prompts"),this.hideAutocomplete()}}hideAutocomplete(){this.autocompleteVisible=!1,this.autocompleteItems=[],this.selectedAutocompleteIndex=0}selectAutocompleteItem(){let e=this.autocompleteItems[this.selectedAutocompleteIndex];if(!e)return;let t=null;if(this.autocompleteTrigger==="/"){let i=e,o=i.parameterFormat;if(console.log(i),o===void 0)this.message=`/${e.name}`;else if(o==="")this.message=`/${e.name} `;else{this.message=`/${e.name} ${o}`;let r=this.message.indexOf('=""');r!==-1&&(t=r+2)}}else this.message=`@${e.name} `;this.hideAutocomplete(),setTimeout(()=>{if(this.messageInput?.nativeElement)if(this.messageInput.nativeElement.focus(),t!==null)this.messageInput.nativeElement.setSelectionRange(t,t);else{let i=this.message.length;this.messageInput.nativeElement.setSelectionRange(i,i)}},0)}selectAutocompleteItemByClick(e){this.selectedAutocompleteIndex=e,this.selectAutocompleteItem()}getAutocompleteQuery(){return this.message.substring(1).split(" ")[0]??""}getParameterFormat(e){return e.parameterFormat}hasParameterFormat(e){return this.autocompleteTrigger==="/"&&e.parameterFormat!==void 0}scrollSelectedItemIntoView(){setTimeout(()=>{let e=document.querySelector(".autocomplete-popup");if(!e)return;let t=e.querySelector(".autocomplete-item.selected");t&&t.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},0)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-chat-textarea"]],viewQuery:function(t,i){if(t&1&&Be(Ya,7)(Ga,5),t&2){let o;be(o=xe())&&(i.messageInput=o.first),be(o=xe())&&(i.fileInput=o.first)}},hostBindings:function(t,i){t&1&&w("paste",function(r){return i.onPaste(r)})("click",function(r){return i.onDocumentClick(r)},Io)},inputs:{isDisabled:"isDisabled",showWelcome:"showWelcome",isThinking:"isThinking",isStarting:"isStarting",isSessionInitializing:"isSessionInitializing"},outputs:{filesPasted:"filesPasted",messageSubmitted:"messageSubmitted",voiceRecordingToggled:"voiceRecordingToggled",heightChanged:"heightChanged",stopRequested:"stopRequested",textareaFocused:"textareaFocused"},features:[Ie],decls:7,vars:12,consts:[["messageInput",""],["fileInput",""],[1,"chat-input-container"],[1,"recording-indicator"],[1,"autocomplete-popup"],[1,"input-row","grouped-input"],[1,"message-input",3,"ngModelChange","keydown","input","focus","blur","ngModel","placeholder","disabled"],[1,"actions"],[1,"recording-dot"],["role","option","tabindex","0",1,"autocomplete-item",3,"selected"],["role","option","tabindex","0",1,"autocomplete-item",3,"click","keydown.enter","keydown.space","mouseenter"],[1,"item-name"],[3,"innerHTML"],[1,"parameter-format"],[1,"item-description",3,"innerHTML"],["icon","stop","variant","danger","title","Stop generation",1,"action-btn"],["icon","send","variant","primary",1,"send-btn",3,"title","disabled","hidden","active"],["icon","stop","variant","danger","title","Stop generation",1,"action-btn",3,"action"],["icon","send","variant","primary",1,"send-btn",3,"action","title","disabled"],["variant","default",1,"voice-btn",3,"action","icon","title"],["icon","attach_file","variant","default","title","Upload files (images or documents)",1,"upload-btn",3,"action","disabled"],["type","file","multiple","","accept","image/*,application/pdf,.pdf,.doc,.docx,.txt,.md,.json,.yaml,.yml,.csv,.xml,.html",2,"display","none",3,"change"]],template:function(t,i){if(t&1){let o=E();c(0,"div",2),x(1,Qa,3,0,"div",3),x(2,Ja,3,0,"div",4),c(3,"div",5)(4,"textarea",6,0),pn("ngModelChange",function(a){return C(o),dn(i.message,a)||(i.message=a),y(a)}),w("keydown",function(a){return i.onKeyDown(a)})("input",function(){return i.onInput()})("focus",function(){return C(o),i.isFocused=!0,y(i.textareaFocused.emit())})("blur",function(){return i.isFocused=!1}),d(),x(6,os,4,3,"div",7),d()()}t&2&&(p(),_(i.isRecording?1:-1),p(),_(i.autocompleteVisible?2:-1),p(),fe("focused",i.isFocused)("welcome-mode",i.showWelcome)("is-thinking",i.isThinking),p(),cn("ngModel",i.message),k("placeholder",i.getPlaceholder())("disabled",i.isDisabled),p(2),_(i.isSessionInitializing?-1:6))},dependencies:[Tn,Cn,yn,wn,hr,On],styles:['@keyframes _ngcontent-%COMP%_gradientBorderShift{0%{background-position:0 0}50%{background-position:100% 0}to{background-position:0 0}}.chat-input-container[_ngcontent-%COMP%]{flex-shrink:0;width:100%;position:relative}.thinking-progress[_ngcontent-%COMP%]{position:absolute;top:0;left:0;right:0;height:3px;z-index:1}.thinking-progress[_ngcontent-%COMP%] .mdc-linear-progress__bar-inner{border-top-width:3px}.input-row.grouped-input[_ngcontent-%COMP%]{display:flex;align-items:stretch;background:var(--glass-bg);border-radius:16px;padding:0 .15rem 0 1.25rem;position:relative;transition:border-color .2s,box-shadow .2s,background .3s}.input-row[_ngcontent-%COMP%]{position:relative;background:var(--glass-bg, #1e1e1e)!important;background-clip:padding-box}.input-row[_ngcontent-%COMP%]:before{content:"";position:absolute;inset:-2px;border-radius:inherit;background-size:200% 100%;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 100%);-webkit-mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);mask:linear-gradient(#fff 0 0) content-box,linear-gradient(#fff 0 0);-webkit-mask-composite:xor;mask-composite:exclude;padding:1px;pointer-events:none;z-index:-1;animation:_ngcontent-%COMP%_gradientBorderShift 3s ease-in-out infinite}.input-row.is-thinking[_ngcontent-%COMP%]:before{inset:0;-webkit-mask:none;mask:none;padding:0;opacity:.15;z-index:0;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 100%);background-size:200% 100%;animation:_ngcontent-%COMP%_gradientBorderShift 3s ease-in-out infinite}.input-row.is-thinking[_ngcontent-%COMP%] .message-input[_ngcontent-%COMP%], .input-row.is-thinking[_ngcontent-%COMP%] .action-btn[_ngcontent-%COMP%]{position:relative;z-index:1}.input-row.grouped-input.focused[_ngcontent-%COMP%]:not(.is-thinking):before{background:var(--color-primary);animation:none}.input-row.grouped-input.focused[_ngcontent-%COMP%]:not(.is-thinking){box-shadow:0 0 0 4px #007aff1a}.message-input[_ngcontent-%COMP%]{flex:1;border:none;outline:none;background:transparent!important;box-shadow:none;font-size:1rem;padding:1rem 0;color:var(--color-text);resize:none;field-sizing:content;min-height:36px;max-height:70vh;overflow-y:auto;font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;line-height:1.5}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:transparent}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.message-input[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.message-input[_ngcontent-%COMP%]:focus{outline:none;border:none;box-shadow:none}.message-input[_ngcontent-%COMP%]:disabled{background-color:var(--color-bg-secondary);color:var(--color-text-secondary);cursor:not-allowed;opacity:.6}.message-input[_ngcontent-%COMP%]::placeholder{color:var(--color-text-secondary);transition:opacity .3s ease-in-out}.message-input[_ngcontent-%COMP%]:disabled::placeholder{animation:_ngcontent-%COMP%_thinkingPulsate 2s ease-in-out infinite}@keyframes _ngcontent-%COMP%_thinkingPulsate{0%,to{opacity:.6}50%{opacity:1}}.voice-btn[_ngcontent-%COMP%], .send-btn[_ngcontent-%COMP%], .action-btn[_ngcontent-%COMP%], .upload-btn[_ngcontent-%COMP%]{margin:0}.actions[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex-wrap:wrap;justify-content:center}.voice-btn.recording[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{color:var(--color-error);animation:_ngcontent-%COMP%_pulse 1.5s infinite}.send-btn[_ngcontent-%COMP%]{transition:opacity .4s,margin-left .4s}.send-btn.active[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{opacity:1}.send-btn[_ngcontent-%COMP%]:not(.active) button[_ngcontent-%COMP%]{opacity:0;margin-left:calc(-.5rem - 36px)}.send-btn[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:hover:not(:disabled){color:#fff;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-primary, #3b82f6) 20%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 80%,var(--color-primary, #3b82f6) 100%);background-size:300% auto;animation:sendButtonGradientShift 6s ease-in-out infinite;box-shadow:0 4px 14px #007aff30;transform:scale(1.2)}.send-btn[_ngcontent-%COMP%] button[_ngcontent-%COMP%]:active:not(:disabled){transform:scale(1.3);box-shadow:0 4px 24px #007aff30}.recording-indicator[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;margin-top:.2rem;margin-bottom:.2rem;color:var(--color-error, #ff5555);font-size:.9rem;position:absolute;top:-1.5rem}@keyframes _ngcontent-%COMP%_pulse{0%,to{opacity:1}50%{opacity:.5}}.autocomplete-popup[_ngcontent-%COMP%]{position:absolute;bottom:100%;left:0;right:0;margin-bottom:.5rem;background:var(--glass-bg);-webkit-backdrop-filter:var(--glass-backdrop-blur);backdrop-filter:var(--glass-backdrop-blur);border-radius:12px;box-shadow:0 8px 32px #00000026;border:1px solid var(--color-border);max-height:400px;max-width:500px;overflow-y:auto;z-index:100}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:transparent}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.autocomplete-popup[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%]{padding:.75rem 1rem;cursor:pointer;transition:background .2s;border-left:3px solid transparent}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%]:hover, .autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item.selected[_ngcontent-%COMP%]{background:var(--color-bg-hover)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item.selected[_ngcontent-%COMP%]{border-left-color:var(--color-primary)}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%]{font-weight:600;color:var(--color-text);margin-bottom:.25rem;font-family:SF Mono,Monaco,Menlo,Cascadia Code,Consolas,monospace;font-size:.95rem}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%] strong{font-weight:700;color:var(--color-primary);background:var(--color-primary-light, rgba(99, 102, 241, .1));padding:0 2px;border-radius:2px}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-name[_ngcontent-%COMP%] .parameter-format[_ngcontent-%COMP%]{color:var(--color-text-secondary);font-weight:400;opacity:.7}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-description[_ngcontent-%COMP%]{font-size:.85rem;color:var(--color-text-secondary);line-height:1.3}.autocomplete-popup[_ngcontent-%COMP%] .autocomplete-item[_ngcontent-%COMP%] .item-description[_ngcontent-%COMP%] strong{font-weight:700;color:var(--color-primary);background:var(--color-primary-light, rgba(99, 102, 241, .1))}@media print{.thinking-progress[_ngcontent-%COMP%], .action-btn[_ngcontent-%COMP%], .voice-btn[_ngcontent-%COMP%], .send-btn[_ngcontent-%COMP%], .upload-btn[_ngcontent-%COMP%], .recording-indicator[_ngcontent-%COMP%], .autocomplete-popup[_ngcontent-%COMP%]{display:none!important}}']})};var rs=(n,e)=>e.label;function as(n,e){if(n&1){let t=E();c(0,"button",2),w("click",function(o){let r=C(t).$implicit,a=m();return y(a.executeAction(r,o))}),c(1,"mat-icon"),f(2),d()()}if(n&2){let t=e.$implicit;Ue("title",t.tooltip||t.label),p(),Ue("aria-label",t.label),p(),D(t.icon)}}var In=class n{actions=[];executeAction(e,t){t.stopPropagation(),e.action()}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-message-context-menu"]],inputs:{actions:"actions"},decls:3,vars:0,consts:[[1,"context-menu-wrapper"],["mat-icon-button",""],["mat-icon-button","",3,"click"]],template:function(t,i){t&1&&(c(0,"div",0),me(1,as,3,3,"button",1,rs),d()),t&2&&(p(),ue(i.actions))},dependencies:[_e,We,J],styles:[".context-menu-wrapper[_ngcontent-%COMP%]{position:relative;display:flex;align-items:center}.context-menu-wrapper[_ngcontent-%COMP%] button[_ngcontent-%COMP%]{transform:scale(.75)}"]})};function Oi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var nt=Oi();function Sr(n){nt=n}var Vt={exec:()=>null};function R(n,e=""){let t=typeof n=="string"?n:n.source,i={replace:(o,r)=>{let a=typeof r=="string"?r:r.source;return a=a.replace(ae.caret,"$1"),t=t.replace(o,a),i},getRegex:()=>new RegExp(t,e)};return i}var ae={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:n=>new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}#`),htmlBeginRegex:n=>new RegExp(`^ {0,${Math.min(3,n-1)}}<(?:[a-z].*>|!--)`,"i")},ss=/^(?:[ \t]*(?:\n|$))+/,ls=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,cs=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Ut=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ds=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ii=/(?:[*+-]|\d{1,9}[.)])/,kr=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Mr=R(kr).replace(/bull/g,Ii).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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/).replace(/\|table/g,"").getRegex(),ps=R(kr).replace(/bull/g,Ii).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).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/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Pi=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ms=/^[^\n]+/,Ai=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,us=R(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Ai).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),hs=R(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ii).getRegex(),Rn="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",Di=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,gs=R("^ {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",Di).replace("tag",Rn).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Er=R(Pi).replace("hr",Ut).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",Rn).getRegex(),fs=R(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Er).getRegex(),Ri={blockquote:fs,code:ls,def:us,fences:cs,heading:ds,hr:Ut,html:gs,lheading:Mr,list:hs,newline:ss,paragraph:Er,table:Vt,text:ms},_r=R("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Ut).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\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",Rn).getRegex(),bs=Oe(K({},Ri),{lheading:ps,table:_r,paragraph:R(Pi).replace("hr",Ut).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",_r).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",Rn).getRegex()}),xs=Oe(K({},Ri),{html:R(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Di).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:Vt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:R(Pi).replace("hr",Ut).replace("heading",` *#{1,6} *[^
|
|
4
|
+
]`).replace("lheading",Mr).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()}),_s=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,vs=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Or=/^( {2,}|\\)\n(?!\s*$)/,Cs=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Fn=/[\p{P}\p{S}]/u,Fi=/[\s\p{P}\p{S}]/u,Ir=/[^\s\p{P}\p{S}]/u,ys=R(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Fi).getRegex(),Pr=/(?!~)[\p{P}\p{S}]/u,ws=/(?!~)[\s\p{P}\p{S}]/u,Ts=/(?:[^\s\p{P}\p{S}]|~)/u,Ss=/\[(?:[^\[\]`]|`[^`]*?`)*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)|`[^`]*?`|<(?! )[^<>]*?>/g,Ar=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,ks=R(Ar,"u").replace(/punct/g,Fn).getRegex(),Ms=R(Ar,"u").replace(/punct/g,Pr).getRegex(),Dr="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Es=R(Dr,"gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Fi).replace(/punct/g,Fn).getRegex(),Os=R(Dr,"gu").replace(/notPunctSpace/g,Ts).replace(/punctSpace/g,ws).replace(/punct/g,Pr).getRegex(),Is=R("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Ir).replace(/punctSpace/g,Fi).replace(/punct/g,Fn).getRegex(),Ps=R(/\\(punct)/,"gu").replace(/punct/g,Fn).getRegex(),As=R(/^<(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(),Ds=R(Di).replace("(?:-->|$)","-->").getRegex(),Rs=R("^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",Ds).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),An=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,Fs=R(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",An).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Rr=R(/^!?\[(label)\]\[(ref)\]/).replace("label",An).replace("ref",Ai).getRegex(),Fr=R(/^!?\[(ref)\](?:\[\])?/).replace("ref",Ai).getRegex(),Ns=R("reflink|nolink(?!\\()","g").replace("reflink",Rr).replace("nolink",Fr).getRegex(),vr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ni={_backpedal:Vt,anyPunctuation:Ps,autolink:As,blockSkip:Ss,br:Or,code:vs,del:Vt,emStrongLDelim:ks,emStrongRDelimAst:Es,emStrongRDelimUnd:Is,escape:_s,link:Fs,nolink:Fr,punctuation:ys,reflink:Rr,reflinkSearch:Ns,tag:Rs,text:Cs,url:Vt},Ls=Oe(K({},Ni),{link:R(/^!?\[(label)\]\((.*?)\)/).replace("label",An).getRegex(),reflink:R(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",An).getRegex()}),ki=Oe(K({},Ni),{emStrongRDelimAst:Os,emStrongLDelim:Ms,url:R(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",vr).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\S]|[^\s~\\]))\1(?=[^~]|$)/,text:R(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",vr).getRegex()}),Hs=Oe(K({},ki),{br:R(Or).replace("{2,}","*").getRegex(),text:R(ki.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()}),Pn={normal:Ri,gfm:bs,pedantic:xs},Ht={normal:Ni,gfm:ki,breaks:Hs,pedantic:Ls},zs={"&":"&","<":"<",">":">",'"':""","'":"'"},Cr=n=>zs[n];function Ae(n,e){if(e){if(ae.escapeTest.test(n))return n.replace(ae.escapeReplace,Cr)}else if(ae.escapeTestNoEncode.test(n))return n.replace(ae.escapeReplaceNoEncode,Cr);return n}function yr(n){try{n=encodeURI(n).replace(ae.percentDecode,"%")}catch(e){return null}return n}function wr(n,e){let t=n.replace(ae.findPipe,(r,a,l)=>{let u=!1,b=a;for(;--b>=0&&l[b]==="\\";)u=!u;return u?"|":" |"}),i=t.split(ae.splitPipe),o=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length<e;)i.push("");for(;o<i.length;o++)i[o]=i[o].trim().replace(ae.slashPipe,"|");return i}function zt(n,e,t){let i=n.length;if(i===0)return"";let o=0;for(;o<i;){let r=n.charAt(i-o-1);if(r===e&&!t)o++;else if(r!==e&&t)o++;else break}return n.slice(0,i-o)}function $s(n,e){if(n.indexOf(e[1])===-1)return-1;let t=0;for(let i=0;i<n.length;i++)if(n[i]==="\\")i++;else if(n[i]===e[0])t++;else if(n[i]===e[1]&&(t--,t<0))return i;return t>0?-2:-1}function Tr(n,e,t,i,o){let r=e.href,a=e.title||null,l=n[1].replace(o.other.outputLinkReplace,"$1");i.state.inLink=!0;let u={type:n[0].charAt(0)==="!"?"image":"link",raw:t,href:r,title:a,text:l,tokens:i.inlineTokens(l)};return i.state.inLink=!1,u}function Vs(n,e,t){let i=n.match(t.other.indentCodeCompensation);if(i===null)return e;let o=i[1];return e.split(`
|
|
5
|
+
`).map(r=>{let a=r.match(t.other.beginningSpace);if(a===null)return r;let[l]=a;return l.length>=o.length?r.slice(o.length):r}).join(`
|
|
6
|
+
`)}var Dn=class{options;rules;lexer;constructor(n){this.options=n||nt}space(n){let e=this.rules.block.newline.exec(n);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(n){let e=this.rules.block.code.exec(n);if(e){let t=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?t:zt(t,`
|
|
7
|
+
`)}}}fences(n){let e=this.rules.block.fences.exec(n);if(e){let t=e[0],i=Vs(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(n){let e=this.rules.block.heading.exec(n);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let i=zt(t,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(t=i.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(n){let e=this.rules.block.hr.exec(n);if(e)return{type:"hr",raw:zt(e[0],`
|
|
8
|
+
`)}}blockquote(n){let e=this.rules.block.blockquote.exec(n);if(e){let t=zt(e[0],`
|
|
9
|
+
`).split(`
|
|
10
|
+
`),i="",o="",r=[];for(;t.length>0;){let a=!1,l=[],u;for(u=0;u<t.length;u++)if(this.rules.other.blockquoteStart.test(t[u]))l.push(t[u]),a=!0;else if(!a)l.push(t[u]);else break;t=t.slice(u);let b=l.join(`
|
|
11
|
+
`),S=b.replace(this.rules.other.blockquoteSetextReplace,`
|
|
12
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");i=i?`${i}
|
|
13
|
+
${b}`:b,o=o?`${o}
|
|
14
|
+
${S}`:S;let M=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(S,r,!0),this.lexer.state.top=M,t.length===0)break;let I=r.at(-1);if(I?.type==="code")break;if(I?.type==="blockquote"){let W=I,z=W.raw+`
|
|
15
|
+
`+t.join(`
|
|
16
|
+
`),de=this.blockquote(z);r[r.length-1]=de,i=i.substring(0,i.length-W.raw.length)+de.raw,o=o.substring(0,o.length-W.text.length)+de.text;break}else if(I?.type==="list"){let W=I,z=W.raw+`
|
|
17
|
+
`+t.join(`
|
|
18
|
+
`),de=this.list(z);r[r.length-1]=de,i=i.substring(0,i.length-I.raw.length)+de.raw,o=o.substring(0,o.length-W.raw.length)+de.raw,t=z.substring(r.at(-1).raw.length).split(`
|
|
19
|
+
`);continue}}return{type:"blockquote",raw:i,tokens:r,text:o}}}list(n){let e=this.rules.block.list.exec(n);if(e){let t=e[1].trim(),i=t.length>1,o={type:"list",raw:"",ordered:i,start:i?+t.slice(0,-1):"",loose:!1,items:[]};t=i?`\\d{1,9}\\${t.slice(-1)}`:`\\${t}`,this.options.pedantic&&(t=i?t:"[*+-]");let r=this.rules.other.listItemRegex(t),a=!1;for(;n;){let u=!1,b="",S="";if(!(e=r.exec(n))||this.rules.block.hr.test(n))break;b=e[0],n=n.substring(b.length);let M=e[2].split(`
|
|
20
|
+
`,1)[0].replace(this.rules.other.listReplaceTabs,It=>" ".repeat(3*It.length)),I=n.split(`
|
|
21
|
+
`,1)[0],W=!M.trim(),z=0;if(this.options.pedantic?(z=2,S=M.trimStart()):W?z=e[1].length+1:(z=e[2].search(this.rules.other.nonSpaceChar),z=z>4?1:z,S=M.slice(z),z+=e[1].length),W&&this.rules.other.blankLine.test(I)&&(b+=I+`
|
|
22
|
+
`,n=n.substring(I.length+1),u=!0),!u){let It=this.rules.other.nextBulletRegex(z),Qt=this.rules.other.hrRegex(z),Xe=this.rules.other.fencesBeginRegex(z),Q=this.rules.other.headingBeginRegex(z),Qe=this.rules.other.htmlBeginRegex(z);for(;n;){let Ze=n.split(`
|
|
23
|
+
`,1)[0],Ke;if(I=Ze,this.options.pedantic?(I=I.replace(this.rules.other.listReplaceNesting," "),Ke=I):Ke=I.replace(this.rules.other.tabCharGlobal," "),Xe.test(I)||Q.test(I)||Qe.test(I)||It.test(I)||Qt.test(I))break;if(Ke.search(this.rules.other.nonSpaceChar)>=z||!I.trim())S+=`
|
|
24
|
+
`+Ke.slice(z);else{if(W||M.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Xe.test(M)||Q.test(M)||Qt.test(M))break;S+=`
|
|
25
|
+
`+I}!W&&!I.trim()&&(W=!0),b+=Ze+`
|
|
26
|
+
`,n=n.substring(Ze.length+1),M=Ke.slice(z)}}o.loose||(a?o.loose=!0:this.rules.other.doubleBlankLine.test(b)&&(a=!0));let de=null,Xt;this.options.gfm&&(de=this.rules.other.listIsTask.exec(S),de&&(Xt=de[0]!=="[ ] ",S=S.replace(this.rules.other.listReplaceTask,""))),o.items.push({type:"list_item",raw:b,task:!!de,checked:Xt,loose:!1,text:S,tokens:[]}),o.raw+=b}let l=o.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let u=0;u<o.items.length;u++)if(this.lexer.state.top=!1,o.items[u].tokens=this.lexer.blockTokens(o.items[u].text,[]),!o.loose){let b=o.items[u].tokens.filter(M=>M.type==="space"),S=b.length>0&&b.some(M=>this.rules.other.anyLine.test(M.raw));o.loose=S}if(o.loose)for(let u=0;u<o.items.length;u++)o.items[u].loose=!0;return o}}html(n){let e=this.rules.block.html.exec(n);if(e)return{type:"html",block:!0,raw:e[0],pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:e[0]}}def(n){let e=this.rules.block.def.exec(n);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),i=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:e[0],href:i,title:o}}}table(n){let e=this.rules.block.table.exec(n);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=wr(e[1]),i=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
27
|
+
`):[],r={type:"table",raw:e[0],header:[],align:[],rows:[]};if(t.length===i.length){for(let a of i)this.rules.other.tableAlignRight.test(a)?r.align.push("right"):this.rules.other.tableAlignCenter.test(a)?r.align.push("center"):this.rules.other.tableAlignLeft.test(a)?r.align.push("left"):r.align.push(null);for(let a=0;a<t.length;a++)r.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:r.align[a]});for(let a of o)r.rows.push(wr(a,r.header.length).map((l,u)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:r.align[u]})));return r}}lheading(n){let e=this.rules.block.lheading.exec(n);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(n){let e=this.rules.block.paragraph.exec(n);if(e){let t=e[1].charAt(e[1].length-1)===`
|
|
28
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(n){let e=this.rules.block.text.exec(n);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(n){let e=this.rules.inline.escape.exec(n);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(n){let e=this.rules.inline.tag.exec(n);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(n){let e=this.rules.inline.link.exec(n);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let r=zt(t.slice(0,-1),"\\");if((t.length-r.length)%2===0)return}else{let r=$s(e[2],"()");if(r===-2)return;if(r>-1){let a=(e[0].indexOf("!")===0?5:4)+e[1].length+r;e[2]=e[2].substring(0,r),e[0]=e[0].substring(0,a).trim(),e[3]=""}}let i=e[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(i);r&&(i=r[1],o=r[3])}else o=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?i=i.slice(1):i=i.slice(1,-1)),Tr(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(n,e){let t;if((t=this.rules.inline.reflink.exec(n))||(t=this.rules.inline.nolink.exec(n))){let i=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[i.toLowerCase()];if(!o){let r=t[0].charAt(0);return{type:"text",raw:r,text:r}}return Tr(t,o,t[0],this.lexer,this.rules)}}emStrong(n,e,t=""){let i=this.rules.inline.emStrongLDelim.exec(n);if(!(!i||i[3]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[2])||!t||this.rules.inline.punctuation.exec(t))){let o=[...i[0]].length-1,r,a,l=o,u=0,b=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(b.lastIndex=0,e=e.slice(-1*n.length+o);(i=b.exec(e))!=null;){if(r=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!r)continue;if(a=[...r].length,i[3]||i[4]){l+=a;continue}else if((i[5]||i[6])&&o%3&&!((o+a)%3)){u+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l+u);let S=[...i[0]][0].length,M=n.slice(0,o+i.index+S+a);if(Math.min(o,a)%2){let W=M.slice(1,-1);return{type:"em",raw:M,text:W,tokens:this.lexer.inlineTokens(W)}}let I=M.slice(2,-2);return{type:"strong",raw:M,text:I,tokens:this.lexer.inlineTokens(I)}}}}codespan(n){let e=this.rules.inline.code.exec(n);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(t),o=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return i&&o&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(n){let e=this.rules.inline.br.exec(n);if(e)return{type:"br",raw:e[0]}}del(n){let e=this.rules.inline.del.exec(n);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(n){let e=this.rules.inline.autolink.exec(n);if(e){let t,i;return e[2]==="@"?(t=e[1],i="mailto:"+t):(t=e[1],i=t),{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}url(n){let e;if(e=this.rules.inline.url.exec(n)){let t,i;if(e[2]==="@")t=e[0],i="mailto:"+t;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);t=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:t,href:i,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(n){let e=this.rules.inline.text.exec(n);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},Te=class Mi{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||nt,this.options.tokenizer=this.options.tokenizer||new Dn,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:ae,block:Pn.normal,inline:Ht.normal};this.options.pedantic?(t.block=Pn.pedantic,t.inline=Ht.pedantic):this.options.gfm&&(t.block=Pn.gfm,this.options.breaks?t.inline=Ht.breaks:t.inline=Ht.gfm),this.tokenizer.rules=t}static get rules(){return{block:Pn,inline:Ht}}static lex(e,t){return new Mi(t).lex(e)}static lexInline(e,t){return new Mi(t).inlineTokens(e)}lex(e){e=e.replace(ae.carriageReturn,`
|
|
29
|
+
`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let i=this.inlineQueue[t];this.inlineTokens(i.src,i.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],i=!1){for(this.options.pedantic&&(e=e.replace(ae.tabCharGlobal," ").replace(ae.spaceLine,""));e;){let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=t.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
|
|
30
|
+
`:t.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
31
|
+
`)?"":`
|
|
32
|
+
`)+o.raw,a.text+=`
|
|
33
|
+
`+o.text,this.inlineQueue.at(-1).src=a.text):t.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
34
|
+
`)?"":`
|
|
35
|
+
`)+o.raw,a.text+=`
|
|
36
|
+
`+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},t.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),t.push(o);continue}let r=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(b=>{u=b.call({lexer:this},l),typeof u=="number"&&u>=0&&(a=Math.min(a,u))}),a<1/0&&a>=0&&(r=e.substring(0,a+1))}if(this.state.top&&(o=this.tokenizer.paragraph(r))){let a=t.at(-1);i&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
|
|
37
|
+
`)?"":`
|
|
38
|
+
`)+o.raw,a.text+=`
|
|
39
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(o),i=r.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let a=t.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
40
|
+
`)?"":`
|
|
41
|
+
`)+o.raw,a.text+=`
|
|
42
|
+
`+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(o);continue}if(e){let a="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(a);break}else throw new Error(a)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let i=e,o=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)l.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,o.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(o=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let r=!1,a="";for(;e;){r||(a=""),r=!1;let l;if(this.options.extensions?.inline?.some(b=>(l=b.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let b=t.at(-1);l.type==="text"&&b?.type==="text"?(b.raw+=l.raw,b.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,i,a)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let u=e;if(this.options.extensions?.startInline){let b=1/0,S=e.slice(1),M;this.options.extensions.startInline.forEach(I=>{M=I.call({lexer:this},S),typeof M=="number"&&M>=0&&(b=Math.min(b,M))}),b<1/0&&b>=0&&(u=e.substring(0,b+1))}if(l=this.tokenizer.inlineText(u)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(a=l.raw.slice(-1)),r=!0;let b=t.at(-1);b?.type==="text"?(b.raw+=l.raw,b.text+=l.text):t.push(l);continue}if(e){let b="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(b);break}else throw new Error(b)}}return t}},bt=class{options;parser;constructor(n){this.options=n||nt}space(n){return""}code({text:n,lang:e,escaped:t}){let i=(e||"").match(ae.notSpaceStart)?.[0],o=n.replace(ae.endingNewline,"")+`
|
|
43
|
+
`;return i?'<pre><code class="language-'+Ae(i)+'">'+(t?o:Ae(o,!0))+`</code></pre>
|
|
44
|
+
`:"<pre><code>"+(t?o:Ae(o,!0))+`</code></pre>
|
|
45
|
+
`}blockquote({tokens:n}){return`<blockquote>
|
|
46
|
+
${this.parser.parse(n)}</blockquote>
|
|
47
|
+
`}html({text:n}){return n}def(n){return""}heading({tokens:n,depth:e}){return`<h${e}>${this.parser.parseInline(n)}</h${e}>
|
|
48
|
+
`}hr(n){return`<hr>
|
|
49
|
+
`}list(n){let e=n.ordered,t=n.start,i="";for(let a=0;a<n.items.length;a++){let l=n.items[a];i+=this.listitem(l)}let o=e?"ol":"ul",r=e&&t!==1?' start="'+t+'"':"";return"<"+o+r+`>
|
|
50
|
+
`+i+"</"+o+`>
|
|
51
|
+
`}listitem(n){let e="";if(n.task){let t=this.checkbox({checked:!!n.checked});n.loose?n.tokens[0]?.type==="paragraph"?(n.tokens[0].text=t+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&n.tokens[0].tokens[0].type==="text"&&(n.tokens[0].tokens[0].text=t+" "+Ae(n.tokens[0].tokens[0].text),n.tokens[0].tokens[0].escaped=!0)):n.tokens.unshift({type:"text",raw:t+" ",text:t+" ",escaped:!0}):e+=t+" "}return e+=this.parser.parse(n.tokens,!!n.loose),`<li>${e}</li>
|
|
52
|
+
`}checkbox({checked:n}){return"<input "+(n?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:n}){return`<p>${this.parser.parseInline(n)}</p>
|
|
53
|
+
`}table(n){let e="",t="";for(let o=0;o<n.header.length;o++)t+=this.tablecell(n.header[o]);e+=this.tablerow({text:t});let i="";for(let o=0;o<n.rows.length;o++){let r=n.rows[o];t="";for(let a=0;a<r.length;a++)t+=this.tablecell(r[a]);i+=this.tablerow({text:t})}return i&&(i=`<tbody>${i}</tbody>`),`<table>
|
|
54
|
+
<thead>
|
|
55
|
+
`+e+`</thead>
|
|
56
|
+
`+i+`</table>
|
|
57
|
+
`}tablerow({text:n}){return`<tr>
|
|
58
|
+
${n}</tr>
|
|
59
|
+
`}tablecell(n){let e=this.parser.parseInline(n.tokens),t=n.header?"th":"td";return(n.align?`<${t} align="${n.align}">`:`<${t}>`)+e+`</${t}>
|
|
60
|
+
`}strong({tokens:n}){return`<strong>${this.parser.parseInline(n)}</strong>`}em({tokens:n}){return`<em>${this.parser.parseInline(n)}</em>`}codespan({text:n}){return`<code>${Ae(n,!0)}</code>`}br(n){return"<br>"}del({tokens:n}){return`<del>${this.parser.parseInline(n)}</del>`}link({href:n,title:e,tokens:t}){let i=this.parser.parseInline(t),o=yr(n);if(o===null)return i;n=o;let r='<a href="'+n+'"';return e&&(r+=' title="'+Ae(e)+'"'),r+=">"+i+"</a>",r}image({href:n,title:e,text:t,tokens:i}){i&&(t=this.parser.parseInline(i,this.parser.textRenderer));let o=yr(n);if(o===null)return Ae(t);n=o;let r=`<img src="${n}" alt="${t}"`;return e&&(r+=` title="${Ae(e)}"`),r+=">",r}text(n){return"tokens"in n&&n.tokens?this.parser.parseInline(n.tokens):"escaped"in n&&n.escaped?n.text:Ae(n.text)}},Li=class{strong({text:n}){return n}em({text:n}){return n}codespan({text:n}){return n}del({text:n}){return n}html({text:n}){return n}text({text:n}){return n}link({text:n}){return""+n}image({text:n}){return""+n}br(){return""}},Se=class Ei{options;renderer;textRenderer;constructor(e){this.options=e||nt,this.options.renderer=this.options.renderer||new bt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Li}static parse(e,t){return new Ei(t).parse(e)}static parseInline(e,t){return new Ei(t).parseInline(e)}parse(e,t=!0){let i="";for(let o=0;o<e.length;o++){let r=e[o];if(this.options.extensions?.renderers?.[r.type]){let l=r,u=this.options.extensions.renderers[l.type].call({parser:this},l);if(u!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(l.type)){i+=u||"";continue}}let a=r;switch(a.type){case"space":{i+=this.renderer.space(a);continue}case"hr":{i+=this.renderer.hr(a);continue}case"heading":{i+=this.renderer.heading(a);continue}case"code":{i+=this.renderer.code(a);continue}case"table":{i+=this.renderer.table(a);continue}case"blockquote":{i+=this.renderer.blockquote(a);continue}case"list":{i+=this.renderer.list(a);continue}case"html":{i+=this.renderer.html(a);continue}case"def":{i+=this.renderer.def(a);continue}case"paragraph":{i+=this.renderer.paragraph(a);continue}case"text":{let l=a,u=this.renderer.text(l);for(;o+1<e.length&&e[o+1].type==="text";)l=e[++o],u+=`
|
|
61
|
+
`+this.renderer.text(l);t?i+=this.renderer.paragraph({type:"paragraph",raw:u,text:u,tokens:[{type:"text",raw:u,text:u,escaped:!0}]}):i+=u;continue}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return i}parseInline(e,t=this.renderer){let i="";for(let o=0;o<e.length;o++){let r=e[o];if(this.options.extensions?.renderers?.[r.type]){let l=this.options.extensions.renderers[r.type].call({parser:this},r);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){i+=l||"";continue}}let a=r;switch(a.type){case"escape":{i+=t.text(a);break}case"html":{i+=t.html(a);break}case"link":{i+=t.link(a);break}case"image":{i+=t.image(a);break}case"strong":{i+=t.strong(a);break}case"em":{i+=t.em(a);break}case"codespan":{i+=t.codespan(a);break}case"br":{i+=t.br(a);break}case"del":{i+=t.del(a);break}case"text":{i+=t.text(a);break}default:{let l='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return i}},$t=class{options;block;constructor(n){this.options=n||nt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(n){return n}postprocess(n){return n}processAllTokens(n){return n}emStrongMask(n){return n}provideLexer(){return this.block?Te.lex:Te.lexInline}provideParser(){return this.block?Se.parse:Se.parseInline}},Us=class{defaults=Oi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Se;Renderer=bt;TextRenderer=Li;Lexer=Te;Tokenizer=Dn;Hooks=$t;constructor(...n){this.use(...n)}walkTokens(n,e){let t=[];for(let i of n)switch(t=t.concat(e.call(this,i)),i.type){case"table":{let o=i;for(let r of o.header)t=t.concat(this.walkTokens(r.tokens,e));for(let r of o.rows)for(let a of r)t=t.concat(this.walkTokens(a.tokens,e));break}case"list":{let o=i;t=t.concat(this.walkTokens(o.items,e));break}default:{let o=i;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let a=o[r].flat(1/0);t=t.concat(this.walkTokens(a,e))}):o.tokens&&(t=t.concat(this.walkTokens(o.tokens,e)))}}return t}use(...n){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(t=>{let i=K({},t);if(i.async=this.defaults.async||i.async||!1,t.extensions&&(t.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=e.renderers[o.name];r?e.renderers[o.name]=function(...a){let l=o.renderer.apply(this,a);return l===!1&&(l=r.apply(this,a)),l}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=e[o.level];r?r.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),i.extensions=e),t.renderer){let o=this.defaults.renderer||new bt(this.defaults);for(let r in t.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let a=r,l=t.renderer[a],u=o[a];o[a]=(...b)=>{let S=l.apply(o,b);return S===!1&&(S=u.apply(o,b)),S||""}}i.renderer=o}if(t.tokenizer){let o=this.defaults.tokenizer||new Dn(this.defaults);for(let r in t.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let a=r,l=t.tokenizer[a],u=o[a];o[a]=(...b)=>{let S=l.apply(o,b);return S===!1&&(S=u.apply(o,b)),S}}i.tokenizer=o}if(t.hooks){let o=this.defaults.hooks||new $t;for(let r in t.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let a=r,l=t.hooks[a],u=o[a];$t.passThroughHooks.has(r)?o[a]=b=>{if(this.defaults.async&&$t.passThroughHooksRespectAsync.has(r))return L(this,null,function*(){let M=yield l.call(o,b);return u.call(o,M)});let S=l.call(o,b);return u.call(o,S)}:o[a]=(...b)=>{if(this.defaults.async)return L(this,null,function*(){let M=yield l.apply(o,b);return M===!1&&(M=yield u.apply(o,b)),M});let S=l.apply(o,b);return S===!1&&(S=u.apply(o,b)),S}}i.hooks=o}if(t.walkTokens){let o=this.defaults.walkTokens,r=t.walkTokens;i.walkTokens=function(a){let l=[];return l.push(r.call(this,a)),o&&(l=l.concat(o.call(this,a))),l}}this.defaults=K(K({},this.defaults),i)}),this}setOptions(n){return this.defaults=K(K({},this.defaults),n),this}lexer(n,e){return Te.lex(n,e??this.defaults)}parser(n,e){return Se.parse(n,e??this.defaults)}parseMarkdown(n){return(e,t)=>{let i=K({},t),o=K(K({},this.defaults),i),r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&i.async===!1)return r(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=n),o.async)return L(this,null,function*(){let a=o.hooks?yield o.hooks.preprocess(e):e,l=yield(o.hooks?yield o.hooks.provideLexer():n?Te.lex:Te.lexInline)(a,o),u=o.hooks?yield o.hooks.processAllTokens(l):l;o.walkTokens&&(yield Promise.all(this.walkTokens(u,o.walkTokens)));let b=yield(o.hooks?yield o.hooks.provideParser():n?Se.parse:Se.parseInline)(u,o);return o.hooks?yield o.hooks.postprocess(b):b}).catch(r);try{o.hooks&&(e=o.hooks.preprocess(e));let a=(o.hooks?o.hooks.provideLexer():n?Te.lex:Te.lexInline)(e,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let l=(o.hooks?o.hooks.provideParser():n?Se.parse:Se.parseInline)(a,o);return o.hooks&&(l=o.hooks.postprocess(l)),l}catch(a){return r(a)}}}onError(n,e){return t=>{if(t.message+=`
|
|
62
|
+
Please report this to https://github.com/markedjs/marked.`,n){let i="<p>An error occurred:</p><pre>"+Ae(t.message+"",!0)+"</pre>";return e?Promise.resolve(i):i}if(e)return Promise.reject(t);throw t}}},tt=new Us;function N(n,e){return tt.parse(n,e)}N.options=N.setOptions=function(n){return tt.setOptions(n),N.defaults=tt.defaults,Sr(N.defaults),N};N.getDefaults=Oi;N.defaults=nt;N.use=function(...n){return tt.use(...n),N.defaults=tt.defaults,Sr(N.defaults),N};N.walkTokens=function(n,e){return tt.walkTokens(n,e)};N.parseInline=tt.parseInline;N.Parser=Se;N.parser=Se.parse;N.Renderer=bt;N.TextRenderer=Li;N.Lexer=Te;N.lexer=Te.lex;N.Tokenizer=Dn;N.Hooks=$t;N.parse=N;var pp=N.options,mp=N.setOptions,up=N.use,hp=N.walkTokens,gp=N.parseInline;var fp=Se.parse,bp=Te.lex;var{entries:jr,setPrototypeOf:Nr,isFrozen:Bs,getPrototypeOf:js,getOwnPropertyDescriptor:Ws}=Object,{freeze:le,seal:ye,create:ji}=Object,{apply:Wi,construct:qi}=typeof Reflect<"u"&&Reflect;le||(le=function(e){return e});ye||(ye=function(e){return e});Wi||(Wi=function(e,t){for(var i=arguments.length,o=new Array(i>2?i-2:0),r=2;r<i;r++)o[r-2]=arguments[r];return e.apply(t,o)});qi||(qi=function(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];return new e(...i)});var Nn=ce(Array.prototype.forEach),qs=ce(Array.prototype.lastIndexOf),Lr=ce(Array.prototype.pop),Bt=ce(Array.prototype.push),Ys=ce(Array.prototype.splice),Hn=ce(String.prototype.toLowerCase),Hi=ce(String.prototype.toString),zi=ce(String.prototype.match),jt=ce(String.prototype.replace),Gs=ce(String.prototype.indexOf),Xs=ce(String.prototype.trim),ke=ce(Object.prototype.hasOwnProperty),se=ce(RegExp.prototype.test),Wt=Qs(TypeError);function ce(n){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var t=arguments.length,i=new Array(t>1?t-1:0),o=1;o<t;o++)i[o-1]=arguments[o];return Wi(n,e,i)}}function Qs(n){return function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];return qi(n,t)}}function O(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Hn;Nr&&Nr(n,null);let i=e.length;for(;i--;){let o=e[i];if(typeof o=="string"){let r=t(o);r!==o&&(Bs(e)||(e[i]=r),o=r)}n[o]=!0}return n}function Zs(n){for(let e=0;e<n.length;e++)ke(n,e)||(n[e]=null);return n}function De(n){let e=ji(null);for(let[t,i]of jr(n))ke(n,t)&&(Array.isArray(i)?e[t]=Zs(i):i&&typeof i=="object"&&i.constructor===Object?e[t]=De(i):e[t]=i);return e}function qt(n,e){for(;n!==null;){let i=Ws(n,e);if(i){if(i.get)return ce(i.get);if(typeof i.value=="function")return ce(i.value)}n=js(n)}function t(){return null}return t}var Hr=le(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),$i=le(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Vi=le(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Ks=le(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ui=le(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Js=le(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),zr=le(["#text"]),$r=le(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Bi=le(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Vr=le(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Ln=le(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),el=ye(/\{\{[\w\W]*|[\w\W]*\}\}/gm),tl=ye(/<%[\w\W]*|[\w\W]*%>/gm),nl=ye(/\$\{[\w\W]*/gm),il=ye(/^data-[\-\w.\u00B7-\uFFFF]+$/),ol=ye(/^aria-[\-\w]+$/),Wr=ye(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),rl=ye(/^(?:\w+script|data):/i),al=ye(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),qr=ye(/^html$/i),sl=ye(/^[a-z][.\w]*(-[.\w]+)+$/i),Ur=Object.freeze({__proto__:null,ARIA_ATTR:ol,ATTR_WHITESPACE:al,CUSTOM_ELEMENT:sl,DATA_ATTR:il,DOCTYPE_NAME:qr,ERB_EXPR:tl,IS_ALLOWED_URI:Wr,IS_SCRIPT_OR_DATA:rl,MUSTACHE_EXPR:el,TMPLIT_EXPR:nl}),Yt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},ll=function(){return typeof window>"u"?null:window},cl=function(e,t){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let i=null,o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(i=t.getAttribute(o));let r="dompurify"+(i?"#"+i:"");try{return e.createPolicy(r,{createHTML(a){return a},createScriptURL(a){return a}})}catch(a){return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Br=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Yr(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ll(),e=T=>Yr(T);if(e.version="3.3.1",e.removed=[],!n||!n.document||n.document.nodeType!==Yt.document||!n.Element)return e.isSupported=!1,e;let{document:t}=n,i=t,o=i.currentScript,{DocumentFragment:r,HTMLTemplateElement:a,Node:l,Element:u,NodeFilter:b,NamedNodeMap:S=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:M,DOMParser:I,trustedTypes:W}=n,z=u.prototype,de=qt(z,"cloneNode"),Xt=qt(z,"remove"),It=qt(z,"nextSibling"),Qt=qt(z,"childNodes"),Xe=qt(z,"parentNode");if(typeof a=="function"){let T=t.createElement("template");T.content&&T.content.ownerDocument&&(t=T.content.ownerDocument)}let Q,Qe="",{implementation:Ze,createNodeIterator:Ke,createDocumentFragment:Pa,getElementsByTagName:Aa}=t,{importNode:Da}=i,ie=Br();e.isSupported=typeof jr=="function"&&typeof Xe=="function"&&Ze&&Ze.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:ri,ERB_EXPR:ai,TMPLIT_EXPR:si,DATA_ATTR:Ra,ARIA_ATTR:Fa,IS_SCRIPT_OR_DATA:Na,ATTR_WHITESPACE:Ji,CUSTOM_ELEMENT:La}=Ur,{IS_ALLOWED_URI:eo}=Ur,Z=null,to=O({},[...Hr,...$i,...Vi,...Ui,...zr]),ee=null,no=O({},[...$r,...Bi,...Vr,...Ln]),j=Object.seal(ji(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Pt=null,li=null,rt=Object.seal(ji(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),io=!0,ci=!0,oo=!1,ro=!0,at=!1,Zt=!0,Je=!1,di=!1,pi=!1,st=!1,Kt=!1,Jt=!1,ao=!0,so=!1,Ha="user-content-",mi=!0,At=!1,lt={},Me=null,ui=O({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),lo=null,co=O({},["audio","video","img","source","image","track"]),hi=null,po=O({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),en="http://www.w3.org/1998/Math/MathML",tn="http://www.w3.org/2000/svg",Fe="http://www.w3.org/1999/xhtml",ct=Fe,gi=!1,fi=null,za=O({},[en,tn,Fe],Hi),nn=O({},["mi","mo","mn","ms","mtext"]),on=O({},["annotation-xml"]),$a=O({},["title","style","font","a","script"]),Dt=null,Va=["application/xhtml+xml","text/html"],Ua="text/html",X=null,dt=null,Ba=t.createElement("form"),mo=function(s){return s instanceof RegExp||s instanceof Function},bi=function(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(dt&&dt===s)){if((!s||typeof s!="object")&&(s={}),s=De(s),Dt=Va.indexOf(s.PARSER_MEDIA_TYPE)===-1?Ua:s.PARSER_MEDIA_TYPE,X=Dt==="application/xhtml+xml"?Hi:Hn,Z=ke(s,"ALLOWED_TAGS")?O({},s.ALLOWED_TAGS,X):to,ee=ke(s,"ALLOWED_ATTR")?O({},s.ALLOWED_ATTR,X):no,fi=ke(s,"ALLOWED_NAMESPACES")?O({},s.ALLOWED_NAMESPACES,Hi):za,hi=ke(s,"ADD_URI_SAFE_ATTR")?O(De(po),s.ADD_URI_SAFE_ATTR,X):po,lo=ke(s,"ADD_DATA_URI_TAGS")?O(De(co),s.ADD_DATA_URI_TAGS,X):co,Me=ke(s,"FORBID_CONTENTS")?O({},s.FORBID_CONTENTS,X):ui,Pt=ke(s,"FORBID_TAGS")?O({},s.FORBID_TAGS,X):De({}),li=ke(s,"FORBID_ATTR")?O({},s.FORBID_ATTR,X):De({}),lt=ke(s,"USE_PROFILES")?s.USE_PROFILES:!1,io=s.ALLOW_ARIA_ATTR!==!1,ci=s.ALLOW_DATA_ATTR!==!1,oo=s.ALLOW_UNKNOWN_PROTOCOLS||!1,ro=s.ALLOW_SELF_CLOSE_IN_ATTR!==!1,at=s.SAFE_FOR_TEMPLATES||!1,Zt=s.SAFE_FOR_XML!==!1,Je=s.WHOLE_DOCUMENT||!1,st=s.RETURN_DOM||!1,Kt=s.RETURN_DOM_FRAGMENT||!1,Jt=s.RETURN_TRUSTED_TYPE||!1,pi=s.FORCE_BODY||!1,ao=s.SANITIZE_DOM!==!1,so=s.SANITIZE_NAMED_PROPS||!1,mi=s.KEEP_CONTENT!==!1,At=s.IN_PLACE||!1,eo=s.ALLOWED_URI_REGEXP||Wr,ct=s.NAMESPACE||Fe,nn=s.MATHML_TEXT_INTEGRATION_POINTS||nn,on=s.HTML_INTEGRATION_POINTS||on,j=s.CUSTOM_ELEMENT_HANDLING||{},s.CUSTOM_ELEMENT_HANDLING&&mo(s.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(j.tagNameCheck=s.CUSTOM_ELEMENT_HANDLING.tagNameCheck),s.CUSTOM_ELEMENT_HANDLING&&mo(s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(j.attributeNameCheck=s.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),s.CUSTOM_ELEMENT_HANDLING&&typeof s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(j.allowCustomizedBuiltInElements=s.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),at&&(ci=!1),Kt&&(st=!0),lt&&(Z=O({},zr),ee=[],lt.html===!0&&(O(Z,Hr),O(ee,$r)),lt.svg===!0&&(O(Z,$i),O(ee,Bi),O(ee,Ln)),lt.svgFilters===!0&&(O(Z,Vi),O(ee,Bi),O(ee,Ln)),lt.mathMl===!0&&(O(Z,Ui),O(ee,Vr),O(ee,Ln))),s.ADD_TAGS&&(typeof s.ADD_TAGS=="function"?rt.tagCheck=s.ADD_TAGS:(Z===to&&(Z=De(Z)),O(Z,s.ADD_TAGS,X))),s.ADD_ATTR&&(typeof s.ADD_ATTR=="function"?rt.attributeCheck=s.ADD_ATTR:(ee===no&&(ee=De(ee)),O(ee,s.ADD_ATTR,X))),s.ADD_URI_SAFE_ATTR&&O(hi,s.ADD_URI_SAFE_ATTR,X),s.FORBID_CONTENTS&&(Me===ui&&(Me=De(Me)),O(Me,s.FORBID_CONTENTS,X)),s.ADD_FORBID_CONTENTS&&(Me===ui&&(Me=De(Me)),O(Me,s.ADD_FORBID_CONTENTS,X)),mi&&(Z["#text"]=!0),Je&&O(Z,["html","head","body"]),Z.table&&(O(Z,["tbody"]),delete Pt.tbody),s.TRUSTED_TYPES_POLICY){if(typeof s.TRUSTED_TYPES_POLICY.createHTML!="function")throw Wt('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof s.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Wt('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');Q=s.TRUSTED_TYPES_POLICY,Qe=Q.createHTML("")}else Q===void 0&&(Q=cl(W,o)),Q!==null&&typeof Qe=="string"&&(Qe=Q.createHTML(""));le&&le(s),dt=s}},uo=O({},[...$i,...Vi,...Ks]),ho=O({},[...Ui,...Js]),ja=function(s){let g=Xe(s);(!g||!g.tagName)&&(g={namespaceURI:ct,tagName:"template"});let v=Hn(s.tagName),V=Hn(g.tagName);return fi[s.namespaceURI]?s.namespaceURI===tn?g.namespaceURI===Fe?v==="svg":g.namespaceURI===en?v==="svg"&&(V==="annotation-xml"||nn[V]):!!uo[v]:s.namespaceURI===en?g.namespaceURI===Fe?v==="math":g.namespaceURI===tn?v==="math"&&on[V]:!!ho[v]:s.namespaceURI===Fe?g.namespaceURI===tn&&!on[V]||g.namespaceURI===en&&!nn[V]?!1:!ho[v]&&($a[v]||!uo[v]):!!(Dt==="application/xhtml+xml"&&fi[s.namespaceURI]):!1},Ee=function(s){Bt(e.removed,{element:s});try{Xe(s).removeChild(s)}catch(g){Xt(s)}},et=function(s,g){try{Bt(e.removed,{attribute:g.getAttributeNode(s),from:g})}catch(v){Bt(e.removed,{attribute:null,from:g})}if(g.removeAttribute(s),s==="is")if(st||Kt)try{Ee(g)}catch(v){}else try{g.setAttribute(s,"")}catch(v){}},go=function(s){let g=null,v=null;if(pi)s="<remove></remove>"+s;else{let q=zi(s,/^[\r\n\t ]+/);v=q&&q[0]}Dt==="application/xhtml+xml"&&ct===Fe&&(s='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+s+"</body></html>");let V=Q?Q.createHTML(s):s;if(ct===Fe)try{g=new I().parseFromString(V,Dt)}catch(q){}if(!g||!g.documentElement){g=Ze.createDocument(ct,"template",null);try{g.documentElement.innerHTML=gi?Qe:V}catch(q){}}let ne=g.body||g.documentElement;return s&&v&&ne.insertBefore(t.createTextNode(v),ne.childNodes[0]||null),ct===Fe?Aa.call(g,Je?"html":"body")[0]:Je?g.documentElement:ne},fo=function(s){return Ke.call(s.ownerDocument||s,s,b.SHOW_ELEMENT|b.SHOW_COMMENT|b.SHOW_TEXT|b.SHOW_PROCESSING_INSTRUCTION|b.SHOW_CDATA_SECTION,null)},xi=function(s){return s instanceof M&&(typeof s.nodeName!="string"||typeof s.textContent!="string"||typeof s.removeChild!="function"||!(s.attributes instanceof S)||typeof s.removeAttribute!="function"||typeof s.setAttribute!="function"||typeof s.namespaceURI!="string"||typeof s.insertBefore!="function"||typeof s.hasChildNodes!="function")},bo=function(s){return typeof l=="function"&&s instanceof l};function Ne(T,s,g){Nn(T,v=>{v.call(e,s,g,dt)})}let xo=function(s){let g=null;if(Ne(ie.beforeSanitizeElements,s,null),xi(s))return Ee(s),!0;let v=X(s.nodeName);if(Ne(ie.uponSanitizeElement,s,{tagName:v,allowedTags:Z}),Zt&&s.hasChildNodes()&&!bo(s.firstElementChild)&&se(/<[/\w!]/g,s.innerHTML)&&se(/<[/\w!]/g,s.textContent)||s.nodeType===Yt.progressingInstruction||Zt&&s.nodeType===Yt.comment&&se(/<[/\w]/g,s.data))return Ee(s),!0;if(!(rt.tagCheck instanceof Function&&rt.tagCheck(v))&&(!Z[v]||Pt[v])){if(!Pt[v]&&vo(v)&&(j.tagNameCheck instanceof RegExp&&se(j.tagNameCheck,v)||j.tagNameCheck instanceof Function&&j.tagNameCheck(v)))return!1;if(mi&&!Me[v]){let V=Xe(s)||s.parentNode,ne=Qt(s)||s.childNodes;if(ne&&V){let q=ne.length;for(let pe=q-1;pe>=0;--pe){let Le=de(ne[pe],!0);Le.__removalCount=(s.__removalCount||0)+1,V.insertBefore(Le,It(s))}}}return Ee(s),!0}return s instanceof u&&!ja(s)||(v==="noscript"||v==="noembed"||v==="noframes")&&se(/<\/no(script|embed|frames)/i,s.innerHTML)?(Ee(s),!0):(at&&s.nodeType===Yt.text&&(g=s.textContent,Nn([ri,ai,si],V=>{g=jt(g,V," ")}),s.textContent!==g&&(Bt(e.removed,{element:s.cloneNode()}),s.textContent=g)),Ne(ie.afterSanitizeElements,s,null),!1)},_o=function(s,g,v){if(ao&&(g==="id"||g==="name")&&(v in t||v in Ba))return!1;if(!(ci&&!li[g]&&se(Ra,g))){if(!(io&&se(Fa,g))){if(!(rt.attributeCheck instanceof Function&&rt.attributeCheck(g,s))){if(!ee[g]||li[g]){if(!(vo(s)&&(j.tagNameCheck instanceof RegExp&&se(j.tagNameCheck,s)||j.tagNameCheck instanceof Function&&j.tagNameCheck(s))&&(j.attributeNameCheck instanceof RegExp&&se(j.attributeNameCheck,g)||j.attributeNameCheck instanceof Function&&j.attributeNameCheck(g,s))||g==="is"&&j.allowCustomizedBuiltInElements&&(j.tagNameCheck instanceof RegExp&&se(j.tagNameCheck,v)||j.tagNameCheck instanceof Function&&j.tagNameCheck(v))))return!1}else if(!hi[g]){if(!se(eo,jt(v,Ji,""))){if(!((g==="src"||g==="xlink:href"||g==="href")&&s!=="script"&&Gs(v,"data:")===0&&lo[s])){if(!(oo&&!se(Na,jt(v,Ji,"")))){if(v)return!1}}}}}}}return!0},vo=function(s){return s!=="annotation-xml"&&zi(s,La)},Co=function(s){Ne(ie.beforeSanitizeAttributes,s,null);let{attributes:g}=s;if(!g||xi(s))return;let v={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ee,forceKeepAttr:void 0},V=g.length;for(;V--;){let ne=g[V],{name:q,namespaceURI:pe,value:Le}=ne,pt=X(q),_i=Le,te=q==="value"?_i:Xs(_i);if(v.attrName=pt,v.attrValue=te,v.keepAttr=!0,v.forceKeepAttr=void 0,Ne(ie.uponSanitizeAttribute,s,v),te=v.attrValue,so&&(pt==="id"||pt==="name")&&(et(q,s),te=Ha+te),Zt&&se(/((--!?|])>)|<\/(style|title|textarea)/i,te)){et(q,s);continue}if(pt==="attributename"&&zi(te,"href")){et(q,s);continue}if(v.forceKeepAttr)continue;if(!v.keepAttr){et(q,s);continue}if(!ro&&se(/\/>/i,te)){et(q,s);continue}at&&Nn([ri,ai,si],wo=>{te=jt(te,wo," ")});let yo=X(s.nodeName);if(!_o(yo,pt,te)){et(q,s);continue}if(Q&&typeof W=="object"&&typeof W.getAttributeType=="function"&&!pe)switch(W.getAttributeType(yo,pt)){case"TrustedHTML":{te=Q.createHTML(te);break}case"TrustedScriptURL":{te=Q.createScriptURL(te);break}}if(te!==_i)try{pe?s.setAttributeNS(pe,q,te):s.setAttribute(q,te),xi(s)?Ee(s):Lr(e.removed)}catch(wo){et(q,s)}}Ne(ie.afterSanitizeAttributes,s,null)},Wa=function T(s){let g=null,v=fo(s);for(Ne(ie.beforeSanitizeShadowDOM,s,null);g=v.nextNode();)Ne(ie.uponSanitizeShadowNode,g,null),xo(g),Co(g),g.content instanceof r&&T(g.content);Ne(ie.afterSanitizeShadowDOM,s,null)};return e.sanitize=function(T){let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},g=null,v=null,V=null,ne=null;if(gi=!T,gi&&(T="<!-->"),typeof T!="string"&&!bo(T))if(typeof T.toString=="function"){if(T=T.toString(),typeof T!="string")throw Wt("dirty is not a string, aborting")}else throw Wt("toString is not a function");if(!e.isSupported)return T;if(di||bi(s),e.removed=[],typeof T=="string"&&(At=!1),At){if(T.nodeName){let Le=X(T.nodeName);if(!Z[Le]||Pt[Le])throw Wt("root node is forbidden and cannot be sanitized in-place")}}else if(T instanceof l)g=go("<!---->"),v=g.ownerDocument.importNode(T,!0),v.nodeType===Yt.element&&v.nodeName==="BODY"||v.nodeName==="HTML"?g=v:g.appendChild(v);else{if(!st&&!at&&!Je&&T.indexOf("<")===-1)return Q&&Jt?Q.createHTML(T):T;if(g=go(T),!g)return st?null:Jt?Qe:""}g&&pi&&Ee(g.firstChild);let q=fo(At?T:g);for(;V=q.nextNode();)xo(V),Co(V),V.content instanceof r&&Wa(V.content);if(At)return T;if(st){if(Kt)for(ne=Pa.call(g.ownerDocument);g.firstChild;)ne.appendChild(g.firstChild);else ne=g;return(ee.shadowroot||ee.shadowrootmode)&&(ne=Da.call(i,ne,!0)),ne}let pe=Je?g.outerHTML:g.innerHTML;return Je&&Z["!doctype"]&&g.ownerDocument&&g.ownerDocument.doctype&&g.ownerDocument.doctype.name&&se(qr,g.ownerDocument.doctype.name)&&(pe="<!DOCTYPE "+g.ownerDocument.doctype.name+`>
|
|
63
|
+
`+pe),at&&Nn([ri,ai,si],Le=>{pe=jt(pe,Le," ")}),Q&&Jt?Q.createHTML(pe):pe},e.setConfig=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bi(T),di=!0},e.clearConfig=function(){dt=null,di=!1},e.isValidAttribute=function(T,s,g){dt||bi({});let v=X(T),V=X(s);return _o(v,V,g)},e.addHook=function(T,s){typeof s=="function"&&Bt(ie[T],s)},e.removeHook=function(T,s){if(s!==void 0){let g=qs(ie[T],s);return g===-1?void 0:Ys(ie[T],g,1)[0]}return Lr(ie[T])},e.removeHooks=function(T){ie[T]=[]},e.removeAllHooks=function(){ie=Br()},e}var Gr=Yr();var Re=class n{renderer;constructor(){this.renderer=new bt,this.configureRenderer()}configureRenderer(){let e=this.renderer.link.bind(this.renderer);this.renderer.link=t=>{let i=this.isExternalLink(t.href),o=e(t);if(i){o=o.replace("<a ",'<a target="_blank" rel="noopener noreferrer" ');let r=t.title?`${t.text} - ${t.title} (opens in new tab)`:`${t.text} (opens in new tab)`;o=o.replace("<a ",`<a aria-label="${this.escapeHtml(r)}" `),o=o.replace("</a>",'<span class="external-link-icon" aria-hidden="true">\u2197</span></a>')}return o}}isExternalLink(e){if(!e||e.startsWith("/")||e.startsWith("#")||e.startsWith("?"))return!1;if(e.startsWith("//"))return!0;try{return new URL(e,window.location.href).hostname!==window.location.hostname}catch(t){return!1}}escapeHtml(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,i=>t[i]||i)}parse(e){return L(this,null,function*(){let t=yield N.parse(e,{renderer:this.renderer,breaks:!0,gfm:!0});return Gr.sanitize(t,{ADD_TAGS:["span"],ADD_ATTR:["aria-hidden","aria-label","target","rel"],ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i})})}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var dl=n=>({"user-message-wrapper":n});function pl(n,e){if(n&1&&(c(0,"div",5)(1,"div",9),f(2),d()()),n&2){let t=m(2);p(2),ut(" ",t.message.speaker," ")}}function ml(n,e){if(n&1&&(c(0,"time",7),f(1),d()),n&2){let t=m(2);p(),D(t.formattedTimestamp)}}function ul(n,e){if(n&1&&(c(0,"div",8),A(1,"app-message-context-menu",10),d()),n&2){let t=m(2);p(),k("actions",t.actions)}}function hl(n,e){if(n&1&&(x(0,pl,3,1,"div",5),A(1,"div",6),x(2,ml,2,1,"time",7),x(3,ul,2,1,"div",8)),n&2){let t=m();_(t.shouldShowSpeaker?0:-1),p(),k("innerHTML",t.renderedContent,ge),p(),_(t.formattedTimestamp?2:-1),p(),_(t.isLongMessage&&t.shouldShowActions&&t.message.role==="assistant"?3:-1)}}function gl(n,e){if(n&1&&(c(0,"a",12),f(1,"view"),d()),n&2){let t=m(2);k("href",t.eventLink,Oo)}}function fl(n,e){if(n&1&&(c(0,"div",2),A(1,"span",11),x(2,gl,2,1,"a",12),d()),n&2){let t=m();p(),k("innerHTML",t.renderedContent,ge),p(),_(t.eventLink?2:-1)}}function bl(n,e){if(n&1&&(c(0,"div",3),A(1,"app-message-context-menu",10),d()),n&2){let t=m();p(),k("actions",t.actions)}}function xl(n,e){if(n&1&&(c(0,"div",4),A(1,"app-message-context-menu",10),d()),n&2){let t=m();p(),k("actions",t.actions)}}var xt=class n{destroy$=new oe;message;canDelete=!0;isOtherUser=!1;copyRequested=new H;deleteRequested=new H;renderedContent="";shouldHideTechnical=!1;shouldHideWarning=!1;sanitizer=h(Pe);notificationService=h(fr);preferencesService=h(ve);projectState=h(Ye);threadState=h(gt);markdownService=h(Re);get messageClasses(){return{[this.message.role]:!0,[this.message.type]:!0,"hidden-technical":this.shouldHideTechnical&&this.message.type==="technical","hidden-warning":this.shouldHideWarning&&this.message.type==="warning","other-user":this.isOtherUser}}ngOnInit(){return L(this,null,function*(){yield this.renderMarkdown(),this.preferencesService.hideTechnicalMessages$.pipe(B(this.destroy$)).subscribe(e=>{this.shouldHideTechnical=e}),this.preferencesService.hideWarningMessages$.pipe(B(this.destroy$)).subscribe(e=>{this.shouldHideWarning=e}),this.shouldHideTechnical=this.preferencesService.getHideTechnicalMessages(),this.shouldHideWarning=this.preferencesService.getHideWarningMessages()})}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete()}get shouldShowSpeaker(){return this.message.role==="user"?this.isOtherUser||this.message.speaker.startsWith("@"):this.message.role==="assistant"}get shouldShowActions(){return this.message.role==="user"||this.message.role==="assistant"}get isSimplified(){return this.message.role!=="user"&&this.message.role!=="assistant"}datePipe=h(wi);get formattedTimestamp(){if(this.message.role!=="user"||!this.message.timestamp)return null;let e=new Date().toDateString()===this.message.timestamp.toDateString();return this.datePipe.transform(this.message.timestamp,e?"HH:mm":"dd/MM HH:mm")}get isLongMessage(){let e=this.extractTextContent();return e.length>1e3||e.split(`
|
|
64
|
+
`).length>20}get actions(){let e=[];return this.message.role==="user"&&this.canDelete&&e.push({icon:"delete",label:"Delete from here",tooltip:"Delete this message and all following messages",action:()=>this.onDelete(),destructive:!0}),e.push({icon:"content_copy",label:"Copy message",tooltip:"Copy message content to clipboard",action:()=>this.onCopy()}),e}get eventLink(){if(!this.message.eventId)return null;let e=this.projectState.getSelectedProjectId(),t=this.threadState.getSelectedThreadId();return!e||!t?null:`/api/projects/${e}/threads/${t}/messages/${encodeURIComponent(this.message.eventId)}/formatted`}renderMarkdown(){return L(this,null,function*(){try{let e=yield this.renderRichContent(this.message.content);this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("Error parsing rich content:",e);let t=this.extractTextContent();this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(t)}})}renderRichContent(e){return L(this,null,function*(){let t=[];for(let i of e)if(i.type==="text"){let o=yield this.markdownService.parse(i.content);t.push(`<div class="text-part">${o}</div>`)}else if(i.type==="image"){let o=`data:${i.mimeType};base64,${i.content}`,r=i.source||"Image",a=`
|
|
65
|
+
<div class="image-content">
|
|
66
|
+
<img src="${o}"
|
|
67
|
+
alt="${r}"
|
|
68
|
+
class="message-image"
|
|
69
|
+
style="max-width: 100%; height: auto; margin: 8px 0; border-radius: 8px; cursor: pointer; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: transform 0.2s ease, box-shadow 0.2s ease;"
|
|
70
|
+
onclick="window.open(this.src, '_blank')" />
|
|
71
|
+
</div>
|
|
72
|
+
`;t.push(a)}return t.join("")})}onCopy(){let e=this.extractTextContent();e.trim()&&navigator.clipboard.writeText(e).then(()=>{console.log("[CHAT-MESSAGE] Message copied to clipboard"),this.notificationService.success("Message copied to clipboard")}).catch(t=>{console.error("[CHAT-MESSAGE] Failed to copy message:",t),this.notificationService.error("Failed to copy message")}),this.copyRequested.emit(this.message)}onDelete(){console.log("[CHAT-MESSAGE] Delete requested for message:",this.message.id),this.deleteRequested.emit(this.message)}extractTextContent(){return this.message.content.filter(e=>e.type==="text").map(e=>e.content).join(`
|
|
73
|
+
|
|
74
|
+
`)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-chat-message"]],inputs:{message:"message",canDelete:"canDelete",isOtherUser:"isOtherUser"},outputs:{copyRequested:"copyRequested",deleteRequested:"deleteRequested"},features:[Lo([wi])],decls:6,vars:8,consts:[[1,"message-wrapper",3,"ngClass"],[1,"message",3,"ngClass"],[1,"simple-content","markdown-content"],[1,"actions","assistant-top-actions"],[1,"actions","user-top-actions"],[1,"message-header"],[1,"content","markdown-content",3,"innerHTML"],[1,"message-timestamp"],[1,"actions","bottom-actions"],[1,"speaker"],[3,"actions"],[3,"innerHTML"],["target","_blank",1,"event-link",3,"href"]],template:function(t,i){t&1&&(c(0,"div",0)(1,"div",1),x(2,hl,4,4),x(3,fl,3,2,"div",2),d(),x(4,bl,2,1,"div",3),x(5,xl,2,1,"div",4),d()),t&2&&(k("ngClass",zo(6,dl,i.message.role==="user")),p(),k("ngClass",i.messageClasses),p(),_(i.isSimplified?-1:2),p(),_(i.isSimplified?3:-1),p(),_(!i.isLongMessage&&i.shouldShowActions&&i.message.role==="assistant"?4:-1),p(),_(i.shouldShowActions&&i.message.role==="user"?5:-1))},dependencies:[In,hn],styles:[".message-wrapper[_ngcontent-%COMP%]{margin:0;display:flex;align-items:flex-start;gap:.5rem}.message-wrapper.user-message-wrapper[_ngcontent-%COMP%]{margin:.75rem 0;flex-direction:row-reverse;align-items:flex-start}.message-wrapper.user-message-wrapper[_ngcontent-%COMP%]:has(.other-user){flex-direction:row}.message[_ngcontent-%COMP%]{position:relative}.message.user[_ngcontent-%COMP%]{padding:1rem 1.25rem .5rem}.message.user[_ngcontent-%COMP%] .message-timestamp[_ngcontent-%COMP%]{display:block;text-align:right;font-size:.7rem;color:var(--color-text-secondary, #6272a4);white-space:nowrap;margin-top:.4rem;opacity:.7}.message.user[_ngcontent-%COMP%]{background:var(--color-message-user);border-radius:18px 18px 6px;border:1px solid var(--glass-border);box-shadow:none;backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);width:fit-content;max-width:75%;min-width:120px;word-wrap:break-word;transition:transform .2s ease,box-shadow .2s ease}.message.user[_ngcontent-%COMP%]:hover{transform:translateY(-1px);box-shadow:0 12px 40px #1f268733}.message.user.other-user[_ngcontent-%COMP%]{border-bottom-right-radius:18px;border-bottom-left-radius:6px}.message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.message.system[_ngcontent-%COMP%], .message.technical[_ngcontent-%COMP%]{padding:.5rem .75rem;background:transparent;border:none;box-shadow:none;backdrop-filter:none;-webkit-backdrop-filter:none;margin:0;font-family:SF Mono,Monaco,Menlo,monospace;font-size:.85rem;color:var(--color-text-secondary);max-width:none;width:auto;min-width:auto}.message.system[_ngcontent-%COMP%]:hover, .message.technical[_ngcontent-%COMP%]:hover{transform:none;box-shadow:none}.message.hidden-technical[_ngcontent-%COMP%], .message.hidden-warning[_ngcontent-%COMP%]{display:none!important}.message.error[_ngcontent-%COMP%]{padding:1rem 1.25rem;background:#ff3b301f;border-left:3px solid var(--color-error);color:var(--color-error)}.message.warning[_ngcontent-%COMP%]{padding:1rem 1.25rem;background:#ff95001f;border-left:3px solid var(--color-warning);color:var(--color-warning)}.message-header[_ngcontent-%COMP%]{margin-bottom:.5rem}.speaker[_ngcontent-%COMP%]{font-weight:600;font-size:.85rem;color:var(--color-text-secondary, #6272a4)}.content[_ngcontent-%COMP%]{line-height:1.5}.context-menu-top[_ngcontent-%COMP%]{top:.5rem;right:.5rem;z-index:10}.context-menu-bottom[_ngcontent-%COMP%]{bottom:.5rem;right:.5rem;z-index:10}.user-top-actions[_ngcontent-%COMP%]{display:flex;align-items:flex-start;padding-top:.5rem;opacity:0;transition:opacity .2s ease}.user-message-wrapper[_ngcontent-%COMP%]:hover .user-top-actions[_ngcontent-%COMP%]{opacity:1}.assistant-top-actions[_ngcontent-%COMP%]{display:flex;align-items:flex-start;padding-top:.5rem;opacity:0;transition:opacity .2s ease}.message-wrapper[_ngcontent-%COMP%]:hover .assistant-top-actions[_ngcontent-%COMP%]{opacity:1}.simple-content[_ngcontent-%COMP%]{display:flex}.simple-content[_ngcontent-%COMP%] .event-link[_ngcontent-%COMP%]{margin-left:5px;font-size:.9em;color:var(--color-link, #3498db);text-decoration:none}.simple-content[_ngcontent-%COMP%] .event-link[_ngcontent-%COMP%]:hover{text-decoration:underline}.text-part[_ngcontent-%COMP%]{margin:4px 0}.image-content[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;margin:1em 0}.message-image[_ngcontent-%COMP%]{display:block;max-width:100%;height:auto;margin:8px 0;border-radius:12px;cursor:pointer;box-shadow:var(--glass-shadow);transition:transform .3s ease,box-shadow .3s ease;border:1px solid var(--glass-border)}.message-image[_ngcontent-%COMP%]:hover{transform:scale(1.02) translateY(-2px);box-shadow:0 16px 48px #00000026}@media(max-width:768px){.message-image[_ngcontent-%COMP%]{border-radius:4px;margin:6px 0}}@media(max-width:480px){.message-image[_ngcontent-%COMP%]{margin:4px 0}}"]})};var vl=(n,e)=>e.id;function Cl(n,e){if(n&1&&(c(0,"span",4),f(1),d()),n&2){let t=m();p(),D(t.taskSummary)}}function yl(n,e){n&1&&(c(0,"div",6),A(1,"mat-spinner",8),c(2,"span"),f(3,"Loading..."),d()()),n&2&&(p(),k("diameter",16))}function wl(n,e){if(n&1&&A(0,"app-delegation-inline",9),n&2){let t=m().$implicit;k("subThreadId",t.subThreadId)("agentName",t.delegationAgentName)}}function Tl(n,e){if(n&1&&A(0,"app-chat-message",10),n&2){let t=m().$implicit;k("message",t)("canDelete",!1)}}function Sl(n,e){if(n&1&&x(0,wl,1,2,"app-delegation-inline",9)(1,Tl,1,2,"app-chat-message",10),n&2){let t=e.$implicit;_(t.type==="delegation"?0:1)}}function kl(n,e){if(n&1&&(c(0,"div",7)(1,"div",11),f(2),d()()),n&2){let t=m(2);p(2),D(t.streamingText)}}function Ml(n,e){if(n&1&&(c(0,"div",5),x(1,yl,4,1,"div",6),me(2,Sl,2,1,null,null,vl),x(4,kl,3,1,"div",7),d()),n&2){let t=m();p(),_(t.isLoading&&t.subMessages.length===0?1:-1),p(),ue(t.subMessages),p(2),_(t.streamingText?4:-1)}}var zn=class n{subThreadId;agentName;isExpanded=!1;isLoading=!1;subMessages=[];streamingText="";restLoaded=!1;messageIds=new Set;eventSubscription;codayService=h(Ce);threadApi=h(ht);get taskSummary(){let e=this.subMessages.find(t=>t.role==="user");if(e){let t=e.content.filter(i=>i.type==="text").map(i=>i.content).join(" ");return t.length>120?t.substring(0,120)+"...":t}return""}ngOnInit(){for(let e of this.codayService.getBufferedSubThreadEvents(this.subThreadId))this.handleSubThreadEvent(e);this.eventSubscription=this.codayService.subThreadEvents$.pipe(we(e=>e.threadId===this.subThreadId)).subscribe(e=>this.handleSubThreadEvent(e))}ngOnDestroy(){this.eventSubscription?.unsubscribe()}toggle(){this.isExpanded=!this.isExpanded,this.isExpanded&&!this.restLoaded&&this.loadSubThreadMessages()}loadSubThreadMessages(){this.isLoading=!0,this.threadApi.getThreadMessages(this.subThreadId).subscribe({next:e=>{if(e.messages){for(let t of e.messages){let i=sr(t);i&&this.handleSubThreadEvent(i)}this.subMessages=[...this.subMessages].sort((t,i)=>t.id.localeCompare(i.id))}this.restLoaded=!0,this.isLoading=!1},error:e=>{console.error("[DELEGATION-INLINE] Failed to load sub-thread messages:",e),this.restLoaded=!0,this.isLoading=!1}})}handleSubThreadEvent(e){e instanceof er?this.addMessage({id:e.timestamp,role:"user",speaker:"User",content:[{type:"text",content:e.answer}],timestamp:new Date,type:"text"}):e instanceof nr?this.streamingText+=e.chunk:e instanceof rr?(e.role==="assistant"&&(this.streamingText=""),this.addMessage({id:e.timestamp,role:e.role,speaker:e.name,content:e.content,timestamp:new Date,type:"text"})):e instanceof ir?this.addMessage({id:e.timestamp,role:"system",speaker:"System",content:[{type:"text",content:e.toSingleLineString()}],timestamp:new Date,type:"technical",eventId:e.timestamp}):e instanceof or?this.addMessage({id:e.timestamp,role:"system",speaker:"System",content:[{type:"text",content:e.toSingleLineString()}],timestamp:new Date,type:"technical",eventId:e.timestamp}):e instanceof ar?this.addMessage({id:e.timestamp,role:"system",speaker:e.agentName,content:[{type:"text",content:""}],timestamp:new Date,type:"delegation",subThreadId:e.subThreadId,delegationAgentName:e.agentName}):e instanceof tr&&this.addMessage({id:e.timestamp,role:"system",speaker:e.speaker??"System",content:[{type:"text",content:e.text}],timestamp:new Date,type:"technical"})}addMessage(e){this.messageIds.has(e.id)||(this.messageIds.add(e.id),this.subMessages=[...this.subMessages,e])}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-delegation-inline"]],inputs:{subThreadId:"subThreadId",agentName:"agentName"},decls:8,vars:4,consts:[[1,"delegation-inline"],["role","button","tabindex","0",1,"delegation-header",3,"click","keydown.enter","keydown.space"],[1,"expand-icon"],[1,"agent-name"],[1,"task-summary"],[1,"delegation-body"],[1,"loading"],[1,"streaming-message"],[3,"diameter"],[3,"subThreadId","agentName"],[3,"message","canDelete"],[1,"content"]],template:function(t,i){t&1&&(c(0,"div",0)(1,"div",1),w("click",function(){return i.toggle()})("keydown.enter",function(){return i.toggle()})("keydown.space",function(){return i.toggle()}),c(2,"mat-icon",2),f(3),d(),c(4,"span",3),f(5),d(),x(6,Cl,2,1,"span",4),d(),x(7,Ml,5,2,"div",5),d()),t&2&&(p(3),D(i.isExpanded?"expand_more":"chevron_right"),p(2),D(i.agentName),p(),_(i.taskSummary?6:-1),p(),_(i.isExpanded?7:-1))},dependencies:[n,_e,he,J,vn,_n,xt],styles:[".delegation-inline[_ngcontent-%COMP%]{margin:.5rem 0;border-left:3px solid var(--color-primary, #6366f1);border-radius:4px;background:var(--color-bg-secondary);overflow:hidden}.delegation-header[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem .75rem;cursor:pointer;-webkit-user-select:none;user-select:none}.delegation-header[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.delegation-header[_ngcontent-%COMP%] .expand-icon[_ngcontent-%COMP%]{font-size:18px;width:18px;height:18px;color:var(--color-text-secondary, #94a3b8)}.delegation-header[_ngcontent-%COMP%] .agent-name[_ngcontent-%COMP%]{font-weight:600;color:var(--color-primary, #6366f1);white-space:nowrap}.delegation-header[_ngcontent-%COMP%] .task-summary[_ngcontent-%COMP%]{flex:1;color:var(--color-text-secondary, #94a3b8);font-size:.85rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.delegation-body[_ngcontent-%COMP%]{padding:0 .75rem .75rem 1.5rem;border-top:1px solid var(--color-border-light)}.delegation-body[_ngcontent-%COMP%] .loading[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.75rem 0;color:var(--color-text-secondary, #94a3b8);font-size:.85rem}.delegation-body[_ngcontent-%COMP%] .sub-messages[_ngcontent-%COMP%]{padding:.5rem 0}"]})};var vt=class n{unreadCountSubject=new an(0);unreadCount$=this.unreadCountSubject.asObservable();constructor(){console.log("[UNREAD] Service initialized")}addUnread(){let t=this.unreadCountSubject.value+1;this.unreadCountSubject.next(t),console.log("[UNREAD] Added unread message, total:",t)}markAllAsRead(){this.unreadCountSubject.value>0&&(this.unreadCountSubject.next(0),console.log("[UNREAD] Marked all messages as read"))}getCurrentCount(){return this.unreadCountSubject.value}reset(){this.unreadCountSubject.next(0),console.log("[UNREAD] Counter reset")}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var $n=class n{thinkingPhrases=["Processing request...","Thinking...","Working on it..."];currentThinkingPhrase="Processing request...";thinkingPhraseIndex=0;thinkingInterval=null;ngOnInit(){this.startThinkingAnimation()}ngOnDestroy(){this.stopThinkingAnimation()}startThinkingAnimation(){this.thinkingPhraseIndex=0,this.currentThinkingPhrase=this.thinkingPhrases[0]||"Thinking...",this.thinkingInterval=window.setInterval(()=>{this.thinkingPhraseIndex<this.thinkingPhrases.length-1&&(this.thinkingPhraseIndex++,this.currentThinkingPhrase=this.thinkingPhrases[this.thinkingPhraseIndex]||"Thinking...")},2e3)}stopThinkingAnimation(){this.thinkingInterval&&(clearInterval(this.thinkingInterval),this.thinkingInterval=null),this.thinkingPhraseIndex=0,this.currentThinkingPhrase="Thinking..."}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-thinking-loader"]],decls:8,vars:1,consts:[[1,"message-wrapper"],[1,"message","assistant","thinking-message"],[1,"content"],[1,"thinking-loader"],[1,"logo-container"],["src","CODAY-Logo.png","alt","Coday Logo",1,"coday-logo"],[1,"thinking-text"]],template:function(t,i){t&1&&(Rt(0,"div",0)(1,"div",1)(2,"div",2)(3,"div",3)(4,"div",4),Fo(5,"img",5),Ft(),Rt(6,"p",6),f(7),Ft()()()()()),t&2&&(p(7),D(i.currentThinkingPhrase))},dependencies:[_e],styles:[".message-wrapper[_ngcontent-%COMP%]{margin:0;display:flex;align-items:flex-start;gap:.5rem}.message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.message.thinking-message[_ngcontent-%COMP%] .content[_ngcontent-%COMP%]{line-height:1.5}.thinking-loader[_ngcontent-%COMP%]{display:flex;align-items:center;gap:1rem;padding:.75rem 0}.logo-container[_ngcontent-%COMP%]{position:relative;width:32px;height:32px;display:flex;align-items:center;justify-content:center;flex-shrink:0}.coday-logo[_ngcontent-%COMP%]{width:100%;height:100%;object-fit:contain;animation:_ngcontent-%COMP%_pulse 2s ease-in-out infinite;filter:drop-shadow(0 1px 4px rgba(0,0,0,.1))}.thinking-text[_ngcontent-%COMP%]{font-size:.95rem;font-weight:400;color:var(--color-text-secondary);margin:0;animation:_ngcontent-%COMP%_fadeInOut 2s ease-in-out infinite;letter-spacing:.01em;font-style:italic}@keyframes _ngcontent-%COMP%_pulse{0%,to{transform:scale(1);opacity:1}50%{transform:scale(1.1);opacity:.7}}@keyframes _ngcontent-%COMP%_fadeInOut{0%,to{opacity:.6}50%{opacity:1}}@media(max-width:768px){.logo-container[_ngcontent-%COMP%]{width:28px;height:28px}.thinking-text[_ngcontent-%COMP%]{font-size:.875rem}.thinking-loader[_ngcontent-%COMP%]{gap:.75rem}}@media print{.thinking-loader[_ngcontent-%COMP%]{display:none!important}}"]})};var El=(n,e)=>e.id;function Ol(n,e){if(n&1&&A(0,"app-delegation-inline",3),n&2){let t=m().$implicit;k("subThreadId",t.subThreadId)("agentName",t.delegationAgentName)}}function Il(n,e){if(n&1){let t=E();c(0,"app-chat-message",5),w("copyRequested",function(o){C(t);let r=m(2);return y(r.onCopyMessage(o))})("deleteRequested",function(o){C(t);let r=m(2);return y(r.onDeleteMessage(o))}),d()}if(n&2){let t=m(),i=t.$implicit,o=t.$index,r=m();k("message",i)("canDelete",r.canDeleteMessage(o))("isOtherUser",i.role==="user"&&!!r.currentUsername&&i.speaker!==r.currentUsername)}}function Pl(n,e){if(n&1&&x(0,Ol,1,2,"app-delegation-inline",3)(1,Il,1,3,"app-chat-message",4),n&2){let t=e.$implicit;_(t.type==="delegation"?0:1)}}function Al(n,e){if(n&1&&(c(0,"div",1),A(1,"div",6),d()),n&2){let t=m();p(),k("innerHTML",t.renderedStreamingText,ge)}}function Dl(n,e){n&1&&A(0,"app-thinking-loader")}function Rl(n,e){if(n&1){let t=E();c(0,"button",7),w("click",function(){C(t);let o=m();return y(o.goToBottom())}),c(1,"mat-icon",8),f(2,"arrow_downward"),d()()}}var Vn=class n{messages=[];streamingText="";isThinking=!1;currentUsername="";copyRequested=new H;stopRequested=new H;lastMessageCount=0;destroy$=new oe;renderedStreamingText="";isTracking=!0;showGoToBottom=!1;scrollContainer=null;lastScrollTop=0;NEAR_BOTTOM_THRESHOLD=100;scrollCheckTimeout;isProgrammaticScroll=!1;MESSAGE_FRESHNESS_THRESHOLD=300*1e3;elementRef=h(mt);unreadService=h(vt);voiceSynthesisService=h(xr);preferencesService=h(ve);codayService=h(Ce);markdownService=h(Re);sanitizer=h(Pe);ngOnInit(){this.findScrollContainer(),this.setupFocusListeners()}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete(),this.scrollCheckTimeout&&clearTimeout(this.scrollCheckTimeout),window.removeEventListener("focus",this.handleWindowFocus),window.removeEventListener("blur",this.handleWindowBlur)}ngOnChanges(e){e.streamingText&&(this.renderStreamingText(),this.streamingText&&this.isTracking&&setTimeout(()=>this.scrollToBottom(),0))}ngAfterViewChecked(){if(this.messages.length!==this.lastMessageCount){console.log("[CHAT-HISTORY] Message count changed:",this.lastMessageCount,"->",this.messages.length);let e=this.messages.length-this.lastMessageCount;e>0&&(this.handleNewMessages(e),this.handleVoiceAnnouncement(e)),this.lastMessageCount=this.messages.length,this.isTracking&&this.scrollToBottom()}this.scrollContainer||this.findScrollContainer()}scrollToBottom(){try{this.scrollContainer||this.findScrollContainer(),this.scrollContainer&&(this.isProgrammaticScroll=!0,setTimeout(()=>{this.scrollContainer&&this.scrollContainer.scrollTo({top:this.scrollContainer.scrollHeight,behavior:"smooth"}),setTimeout(()=>{this.isProgrammaticScroll=!1},600)},50))}catch(e){console.error("Error scrolling to bottom:",e)}}trackByMessageId(e,t){return t.id}onCopyMessage(e){let t=e.content.filter(i=>i.type==="text").map(i=>i.content).join(`
|
|
75
|
+
|
|
76
|
+
`);navigator.clipboard.writeText(t).then(()=>console.log("Message copied")).catch(i=>console.error("Failed to copy:",i)),this.copyRequested.emit(e)}onStop(){this.stopRequested.emit()}canDeleteMessage(e){return e===0?!1:!this.isThinking}onDeleteMessage(e){if(console.log("[CHAT-HISTORY] Delete requested for message:",e.id),this.messages.findIndex(o=>o.id===e.id)===0){console.warn("[CHAT-HISTORY] Cannot delete first message");return}if(this.isThinking){console.warn("[CHAT-HISTORY] Cannot delete message while agent is thinking");return}if(e.role!=="user"){console.warn("[CHAT-HISTORY] Can only delete user messages");return}confirm(`Delete this message and all following messages?
|
|
77
|
+
|
|
78
|
+
This action cannot be undone once you post another message.`)&&(console.log("[CHAT-HISTORY] Proceeding with message deletion"),this.codayService.deleteMessage(e.id).subscribe({next:o=>{o.success?console.log("[CHAT-HISTORY] Message deleted successfully"):(console.error("[CHAT-HISTORY] Failed to delete message:",o.error),alert(`Failed to delete message: ${o.error}`))},error:o=>{console.error("[CHAT-HISTORY] Error deleting message:",o),alert(`Error deleting message: ${o.message||"Unknown error"}`)}}))}onScroll(){}findScrollContainer(){let e=this.elementRef.nativeElement;this.scrollContainer=e.closest(".chat-wrapper"),this.scrollContainer?(console.log("[CHAT-HISTORY] Scroll container found"),this.scrollContainer.addEventListener("scroll",this.handleScroll.bind(this)),this.lastScrollTop=this.scrollContainer.scrollTop,this.checkScrollPosition()):(console.warn("[CHAT-HISTORY] Scroll container not found"),setTimeout(()=>this.findScrollContainer(),100))}handleScroll=()=>{if(!this.scrollContainer)return;let e=this.scrollContainer.scrollTop;if(Math.abs(e-this.lastScrollTop)<1){this.lastScrollTop=e;return}if(this.isProgrammaticScroll){this.lastScrollTop=e;return}console.log("[CHAT-HISTORY] User scroll detected - disabling auto-scroll"),this.isTracking&&(this.isTracking=!1,this.showGoToBottom=!0),clearTimeout(this.scrollCheckTimeout),this.scrollCheckTimeout=setTimeout(()=>{this.checkScrollPosition()},500),this.lastScrollTop=e};checkScrollPosition(){if(!this.scrollContainer)return;let{scrollTop:e,scrollHeight:t,clientHeight:i}=this.scrollContainer,r=t-e-i<=this.NEAR_BOTTOM_THRESHOLD;r&&!this.isTracking&&(console.log("[CHAT-HISTORY] Near bottom - re-enabling auto-scroll"),this.isTracking=!0,this.showGoToBottom=!1,this.unreadService.markAllAsRead()),!this.isTracking&&!r&&(this.showGoToBottom=!0)}goToBottom(){console.log("[CHAT-HISTORY] Go to bottom clicked - re-enabling auto-scroll"),this.scrollToBottom(),this.isTracking=!0,this.showGoToBottom=!1,this.unreadService.markAllAsRead()}handleNewMessages(e){let i=this.messages.slice(-e).filter(r=>r.role==="assistant");if(i.length===0){console.log("[CHAT-HISTORY] No new assistant messages to count");return}if(this.shouldMarkNewMessagesAsUnread()){console.log("[CHAT-HISTORY] Marking",i.length,"new assistant messages as unread");for(let r=0;r<i.length;r++)this.unreadService.addUnread()}else console.log("[CHAT-HISTORY] New assistant messages are considered read (user is focused and tracking)")}shouldMarkNewMessagesAsUnread(){return document.hasFocus()?this.isTracking?!1:(console.log("[CHAT-HISTORY] User is not tracking (scrolled up) -> unread"),!0):(console.log("[CHAT-HISTORY] Tab does not have focus -> unread"),!0)}setupFocusListeners(){window.addEventListener("focus",this.handleWindowFocus),window.addEventListener("blur",this.handleWindowBlur)}handleWindowFocus=()=>{console.log("[CHAT-HISTORY] Window gained focus"),this.isTracking&&(console.log("[CHAT-HISTORY] User is tracking and focused -> marking messages as read"),this.unreadService.markAllAsRead())};handleWindowBlur=()=>{console.log("[CHAT-HISTORY] Window lost focus")};handleVoiceAnnouncement(e){if(!this.preferencesService.getVoiceAnnounceEnabled())return;let o=this.messages.slice(-e).filter(l=>l.role==="assistant");if(o.length===0){console.log("[CHAT-HISTORY] No new assistant messages to announce");return}let r=o[o.length-1];if(!r){console.warn("[CHAT-HISTORY] No last assistant message found");return}if(!this.isMessageRecentEnoughForAnnouncement(r)){console.log("[CHAT-HISTORY] Message too old for voice announcement");return}if(this.preferencesService.getVoiceMode()==="notification")console.log("[CHAT-HISTORY] Playing notification sound for new assistant message"),this.voiceSynthesisService.ding();else{let l=this.extractTextContentFromMessage(r);if(l.trim()){console.log("[CHAT-HISTORY] Announcing new assistant message via speech");let b=this.preferencesService.getVoiceReadFullText()?l:this.extractPartialText(l);this.voiceSynthesisService.speak(b).then(S=>{S||console.warn("[CHAT-HISTORY] Failed to announce message via speech")}).catch(S=>{console.error("[CHAT-HISTORY] Error during voice announcement:",S)})}}}isMessageRecentEnoughForAnnouncement(e){try{let t=e.timestamp.getTime();return Date.now()-t<=this.MESSAGE_FRESHNESS_THRESHOLD}catch(t){return console.warn("[CHAT-HISTORY] Error checking message freshness:",t),!0}}extractTextContentFromMessage(e){return e.content.filter(t=>t.type==="text").map(t=>t.content).join(`
|
|
79
|
+
|
|
80
|
+
`)}extractPartialText(e){return e.split(`
|
|
81
|
+
`).filter(a=>a.trim().length>0).reduce((a,l)=>{if(a.paragraphs>=3)return a;let u=l.length>80?1:0;return{paragraphs:a.paragraphs+u,text:a.text+(a.text?`
|
|
82
|
+
`:"")+l}},{paragraphs:0,text:""}).text||e}renderStreamingText(){return L(this,null,function*(){if(!this.streamingText){this.renderedStreamingText="";return}try{let e=yield this.markdownService.parse(this.streamingText);this.renderedStreamingText=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("[CHAT-HISTORY] Error rendering streaming text markdown:",e),this.renderedStreamingText=this.sanitizer.bypassSecurityTrustHtml(this.streamingText)}})}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-chat-history"]],hostBindings:function(t,i){t&1&&w("scroll",function(){return i.onScroll()})},inputs:{messages:"messages",streamingText:"streamingText",isThinking:"isThinking",currentUsername:"currentUsername"},outputs:{copyRequested:"copyRequested",stopRequested:"stopRequested"},features:[Ie],decls:6,vars:3,consts:[[1,"chat-history"],[1,"streaming-message","message","assistant"],["mat-fab","","color","primary","title","Go to bottom",1,"go-to-bottom-btn"],[3,"subThreadId","agentName"],[3,"message","canDelete","isOtherUser"],[3,"copyRequested","deleteRequested","message","canDelete","isOtherUser"],[1,"content","markdown-content",3,"innerHTML"],["mat-fab","","color","primary","title","Go to bottom",1,"go-to-bottom-btn",3,"click"],["fontSet","material-icons-outlined"]],template:function(t,i){t&1&&(c(0,"div",0),me(1,Pl,2,1,null,null,El),x(3,Al,2,1,"div",1),x(4,Dl,1,0,"app-thinking-loader"),x(5,Rl,3,0,"button",2),d()),t&2&&(p(),ue(i.messages),p(2),_(i.streamingText?3:-1),p(),_(i.isThinking?4:-1),p(),_(i.showGoToBottom?5:-1))},dependencies:[xt,J,$n,xn,zn],styles:[".streaming-message.assistant[_ngcontent-%COMP%]{background:transparent;border:none;box-shadow:none;border-radius:0;margin-left:0;margin-right:auto;padding:.5rem 0;width:100%;max-width:none;min-width:0}.streaming-message[_ngcontent-%COMP%] .content[_ngcontent-%COMP%]{color:var(--color-text);line-height:1.5}.go-to-bottom-btn[_ngcontent-%COMP%]{position:fixed!important;bottom:30%!important;right:1rem!important;z-index:1000!important}@media(max-width:768px){.go-to-bottom-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;right:.75rem!important}.go-to-bottom-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}@media print{[_nghost-%COMP%]{display:block!important;height:auto!important;max-height:none!important;overflow:visible!important;position:static!important}.chat-history[_ngcontent-%COMP%]{display:block!important;height:auto!important;max-height:none!important;overflow:visible!important;position:static!important}.go-to-bottom-btn[_ngcontent-%COMP%]{display:none!important}}"]})};var Fl=["buttonContainer"],Nl=["freeTextInput"],Ll=(n,e)=>e.value;function Hl(n,e){n&1&&(c(0,"mat-icon",10),f(1,"keyboard_return"),d())}function zl(n,e){if(n&1){let t=E();c(0,"button",8),w("click",function(){let o=C(t).$implicit,r=m(2);return y(r.onOptionClick(o.value))}),c(1,"span",9),f(2),d(),x(3,Hl,2,0,"mat-icon",10),d()}if(n&2){let t=e.$implicit,i=e.$index,o=m(2);fe("highlighted",i===o.highlightedIndex),k("disabled",t.disabled)("id","choice-option-"+i),Ue("aria-selected",i===o.highlightedIndex),p(2),D(t.label),p(),_(i===o.highlightedIndex?3:-1)}}function $l(n,e){if(n&1){let t=E();c(0,"div",6)(1,"span",11),f(2,"Or type your own answer:"),d(),c(3,"div",12)(4,"input",13,1),pn("ngModelChange",function(o){C(t);let r=m(2);return dn(r.freeTextValue,o)||(r.freeTextValue=o),y(o)}),w("keydown",function(o){C(t);let r=m(2);return y(r.onFreeTextKeyDown(o))}),d(),c(6,"button",14),w("click",function(){C(t);let o=m(2);return y(o.onFreeTextSubmit())}),c(7,"mat-icon"),f(8,"send"),d()()()()}if(n&2){let t=m(2);p(4),cn("ngModel",t.freeTextValue),p(2),k("disabled",!t.freeTextValue.trim())}}function Vl(n,e){if(n&1&&(c(0,"div",7)(1,"mat-icon"),f(2,"search"),d(),c(3,"span"),f(4),d()()),n&2){let t=m(2);p(4),D(t.searchText)}}function Ul(n,e){if(n&1){let t=E();c(0,"div",2),A(1,"div",3),Nt(2,"async"),c(3,"div",4,0),w("keydown",function(o){C(t);let r=m();return y(r.onKeyDown(o))}),me(5,zl,4,7,"button",5,Ll),d(),x(7,$l,9,2,"div",6),x(8,Vl,5,1,"div",7),d()}if(n&2){let t=m();p(),k("innerHTML",$o(2,4,t.renderedLabel$),ge),p(2),Ue("aria-activedescendant","choice-option-"+t.highlightedIndex),p(2),ue(t.options),p(2),_(t.allowFreeText?7:-1),p(),_(t.searchText?8:-1)}}var Un=class n{options=[];allowFreeText=!1;set labelHtml(e){typeof e=="object"?this.renderedLabelSubject.next(e):this.renderLabelMarkdown(e)}isVisible=!1;choiceSelected=new H;buttonContainer;freeTextInput;highlightedIndex=0;searchText="";freeTextValue="";searchTimeout;destroy$=new oe;renderedLabelSubject=new an("");renderedLabel$=this.renderedLabelSubject.asObservable();sanitizer=h(Pe);markdownService=h(Re);ngOnDestroy(){this.renderedLabelSubject.complete(),this.destroy$.next(),this.destroy$.complete(),this.searchTimeout&&clearTimeout(this.searchTimeout)}ngAfterViewInit(){this.isVisible&&this.buttonContainer&&setTimeout(()=>this.focusContainer(),100)}ngOnChanges(e){e.isVisible&&e.isVisible.currentValue&&!e.isVisible.previousValue&&(this.highlightedIndex=0,setTimeout(()=>this.focusContainer(),150)),e.options&&!e.options.firstChange&&(this.highlightedIndex=0,this.searchText="",this.freeTextValue="")}focusContainer(){this.buttonContainer?.nativeElement&&this.buttonContainer.nativeElement.focus()}onKeyDown(e){if(this.options.filter(i=>!i.disabled).length!==0)switch(e.key){case"ArrowDown":e.preventDefault(),this.moveHighlight(1);break;case"ArrowUp":e.preventDefault(),this.moveHighlight(-1);break;case"Enter":case" ":e.preventDefault(),this.selectHighlighted();break;case"Home":e.preventDefault(),this.highlightFirst();break;case"End":e.preventDefault(),this.highlightLast();break;case"Escape":e.preventDefault();break;default:e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&this.handleTypeAhead(e.key);break}}moveHighlight(e){let t=this.options.map((r,a)=>({opt:r,idx:a})).filter(({opt:r})=>!r.disabled).map(({idx:r})=>r);if(t.length===0)return;let o=t.findIndex(r=>r===this.highlightedIndex)+e;if(o>=0&&o<t.length){let r=t[o];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}else if(e===1&&o>=t.length){let r=t[0];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}else if(e===-1&&o<0){let r=t[t.length-1];r!==void 0&&(this.highlightedIndex=r,this.scrollToHighlighted())}}highlightFirst(){let e=this.options.findIndex(t=>!t.disabled);e>=0&&(this.highlightedIndex=e,this.scrollToHighlighted())}highlightLast(){let e=this.options.map((t,i)=>({opt:t,idx:i})).filter(({opt:t})=>!t.disabled).map(({idx:t})=>t);if(e.length>0){let t=e[e.length-1];t!==void 0&&(this.highlightedIndex=t,this.scrollToHighlighted())}}scrollToHighlighted(){setTimeout(()=>{let e=document.getElementById("choice-option-"+this.highlightedIndex);e&&e.scrollIntoView({block:"nearest",behavior:"smooth"})},0)}selectHighlighted(){let e=this.options[this.highlightedIndex];e&&!e.disabled&&this.onOptionClick(e.value)}handleTypeAhead(e){this.searchText+=e.toLowerCase();let t=this.options.findIndex(i=>!i.disabled&&i.label.toLowerCase().startsWith(this.searchText));t>=0&&(this.highlightedIndex=t,this.scrollToHighlighted()),this.searchTimeout&&clearTimeout(this.searchTimeout),this.searchTimeout=setTimeout(()=>{this.searchText=""},1e3)}onOptionClick(e){this.choiceSelected.emit(e)}onFreeTextSubmit(){let e=this.freeTextValue.trim();e&&(this.freeTextValue="",this.choiceSelected.emit(e))}onFreeTextKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.onFreeTextSubmit())}renderLabelMarkdown(e){return L(this,null,function*(){if(!e){this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(""));return}try{let t=yield this.markdownService.parse(e);this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(t))}catch(t){console.error("[CHOICE-SELECT] Error parsing label markdown:",t),this.renderedLabelSubject.next(this.sanitizer.bypassSecurityTrustHtml(e))}})}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-choice-select"]],viewQuery:function(t,i){if(t&1&&Be(Fl,5)(Nl,5),t&2){let o;be(o=xe())&&(i.buttonContainer=o.first),be(o=xe())&&(i.freeTextInput=o.first)}},inputs:{options:"options",allowFreeText:"allowFreeText",labelHtml:"labelHtml",isVisible:"isVisible"},outputs:{choiceSelected:"choiceSelected"},features:[Ie],decls:1,vars:1,consts:[["buttonContainer",""],["freeTextInput",""],[1,"choice-container"],[1,"choice-label",3,"innerHTML"],["role","listbox","tabindex","0",1,"choice-buttons",3,"keydown"],["type","button","role","option",1,"choice-button",3,"highlighted","disabled","id"],[1,"free-text-section"],[1,"search-indicator"],["type","button","role","option",1,"choice-button",3,"click","disabled","id"],[1,"choice-button-label"],[1,"choice-button-icon"],[1,"free-text-hint"],[1,"free-text-input-row"],["type","text","placeholder","Type a custom answer\u2026","aria-label","Custom answer",1,"free-text-input",3,"ngModelChange","keydown","ngModel"],["type","button","aria-label","Send custom answer",1,"free-text-send-btn",3,"click","disabled"]],template:function(t,i){t&1&&x(0,Ul,9,6,"div",2),t&2&&_(i.isVisible?0:-1)},dependencies:[he,J,Tn,Cn,yn,wn,Vo],styles:[".choice-container[_ngcontent-%COMP%]{width:100%;display:flex;flex-direction:column;gap:1rem}.choice-label[_ngcontent-%COMP%]{display:block;font-weight:500;color:var(--color-text);font-size:1rem;line-height:1.5}.choice-label[_ngcontent-%COMP%] p{margin:0 0 .5rem}.choice-label[_ngcontent-%COMP%] p:last-child{margin-bottom:0}.choice-label[_ngcontent-%COMP%] code{background:var(--color-code-bg);padding:.2em .4em;border-radius:4px;font-family:monospace;font-size:.9em}.choice-label[_ngcontent-%COMP%] strong{font-weight:600}.choice-buttons[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.5rem;max-height:400px;overflow-y:auto;padding:.5rem;background:var(--color-background);border:2px solid var(--color-border);border-radius:12px;outline:none}.choice-buttons[_ngcontent-%COMP%]:focus-within{border-color:var(--color-primary);box-shadow:0 0 0 3px #007aff1a}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar{width:8px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-track{background:var(--color-background);border-radius:4px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-thumb{background:var(--color-border);border-radius:4px}.choice-buttons[_ngcontent-%COMP%]::-webkit-scrollbar-thumb:hover{background:var(--color-text-secondary)}.choice-button[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;width:100%;padding:.75rem 1rem;border:1px solid var(--color-border);border-radius:8px;background:var(--color-background);color:var(--color-text);font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;font-size:1rem;text-align:left;cursor:pointer;transition:all .2s ease}.choice-button[_ngcontent-%COMP%]:hover:not(:disabled):not(.highlighted){background:var(--color-bg-hover);border-color:var(--color-primary);transform:translate(2px)}.choice-button.highlighted[_ngcontent-%COMP%]{background:var(--color-primary);color:#fff;border-color:var(--color-primary);box-shadow:0 2px 8px #007aff4d}.choice-button.highlighted[_ngcontent-%COMP%] .choice-button-icon[_ngcontent-%COMP%]{color:#fff}.choice-button[_ngcontent-%COMP%]:disabled{opacity:.5;cursor:not-allowed}.choice-button[_ngcontent-%COMP%]:focus{outline:none}.choice-button-label[_ngcontent-%COMP%]{flex:1;line-height:1.5}.choice-button-icon[_ngcontent-%COMP%]{flex-shrink:0;margin-left:.5rem;font-size:1.2rem;width:1.2rem;height:1.2rem}.free-text-section[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.5rem}.free-text-hint[_ngcontent-%COMP%]{font-size:.85rem;color:var(--color-text-secondary);font-style:italic}.free-text-input-row[_ngcontent-%COMP%]{display:flex;gap:.5rem;align-items:center}.free-text-input[_ngcontent-%COMP%]{flex:1;padding:.625rem .875rem;border:1px solid var(--color-border);border-radius:8px;background:var(--color-background);color:var(--color-text);font-family:-apple-system,BlinkMacSystemFont,SF Pro Display,system-ui,sans-serif;font-size:1rem;outline:none;transition:border-color .2s ease,box-shadow .2s ease}.free-text-input[_ngcontent-%COMP%]:focus{border-color:var(--color-primary);box-shadow:0 0 0 3px #007aff1a}.free-text-input[_ngcontent-%COMP%]::placeholder{color:var(--color-text-secondary);opacity:.7}.free-text-send-btn[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;flex-shrink:0;border:none;border-radius:8px;background:var(--color-primary);color:#fff;cursor:pointer;transition:background .2s ease,opacity .2s ease}.free-text-send-btn[_ngcontent-%COMP%]:hover:not(:disabled){opacity:.9}.free-text-send-btn[_ngcontent-%COMP%]:disabled{opacity:.4;cursor:not-allowed}.free-text-send-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1.2rem;width:1.2rem;height:1.2rem}.search-indicator[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem 1rem;background:var(--color-primary);color:#fff;border-radius:8px;font-size:.9rem;font-weight:500;animation:_ngcontent-%COMP%_fadeIn .2s ease}.search-indicator[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1rem;width:1rem;height:1rem;color:#fff}@keyframes _ngcontent-%COMP%_fadeIn{0%{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:translateY(0)}}@media(max-width:480px){.choice-container[_ngcontent-%COMP%]{gap:.75rem}.choice-label[_ngcontent-%COMP%]{font-size:.95rem}.choice-buttons[_ngcontent-%COMP%]{max-height:300px;gap:.375rem}.choice-button[_ngcontent-%COMP%]{font-size:.95rem;padding:.625rem .875rem}}@media print{.choice-buttons[_ngcontent-%COMP%]{max-height:none;overflow:visible}.search-indicator[_ngcontent-%COMP%]{display:none!important}}"]})};function Bl(n,e){if(n&1){let t=E();c(0,"div",0)(1,"div",1)(2,"mat-icon"),f(3,"lock_open"),d()(),c(4,"div",2)(5,"p",3),f(6,"Authorization required"),d(),c(7,"p",4)(8,"strong"),f(9),d(),f(10," needs your permission to continue. "),d()(),c(11,"div",5)(12,"button",6),w("click",function(){let o=C(t),r=m();return y(r.onCancel(o))}),f(13,"Cancel"),d(),c(14,"button",7),w("click",function(){let o=C(t),r=m();return y(r.onAuthorize(o))}),c(15,"mat-icon"),f(16,"open_in_new"),d(),f(17," Authorize "),d()()()}n&2&&(p(9),D(e.integrationName))}var Bn=class n{oauthService=h(En);pendingRequest=kn(this.oauthService.pendingRequest$,{initialValue:null});onAuthorize(e){this.oauthService.openPopup(e)}onCancel(e){this.oauthService.cancelRequest(e)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-oauth-request-panel"]],decls:1,vars:1,consts:[[1,"oauth-panel"],[1,"oauth-icon"],[1,"oauth-content"],[1,"oauth-title"],[1,"oauth-description"],[1,"oauth-actions"],["type","button",1,"oauth-btn","oauth-btn--cancel",3,"click"],["type","button",1,"oauth-btn","oauth-btn--authorize",3,"click"]],template:function(t,i){if(t&1&&x(0,Bl,18,1,"div",0),t&2){let o;_((o=i.pendingRequest())?0:-1,o)}},dependencies:[he,J],styles:[".oauth-panel[_ngcontent-%COMP%]{display:flex;align-items:center;gap:1rem;padding:1rem;border:1px solid var(--color-border);border-radius:12px;background:var(--color-background);width:100%}@media(max-width:480px){.oauth-panel[_ngcontent-%COMP%]{flex-direction:column;align-items:flex-start}}.oauth-icon[_ngcontent-%COMP%]{flex-shrink:0;display:flex;align-items:center;justify-content:center;width:2.5rem;height:2.5rem;border-radius:50%;background:var(--color-primary);color:#fff}.oauth-icon[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1.25rem;width:1.25rem;height:1.25rem}.oauth-content[_ngcontent-%COMP%]{flex:1;min-width:0}.oauth-title[_ngcontent-%COMP%]{margin:0 0 .25rem;font-weight:600;font-size:.95rem;color:var(--color-text)}.oauth-description[_ngcontent-%COMP%]{margin:0;font-size:.875rem;color:var(--color-text-secondary)}.oauth-actions[_ngcontent-%COMP%]{display:flex;gap:.5rem;flex-shrink:0}.oauth-btn[_ngcontent-%COMP%]{display:inline-flex;align-items:center;gap:.375rem;padding:.5rem 1rem;border-radius:8px;border:1px solid var(--color-border);font-size:.9rem;font-family:inherit;cursor:pointer;transition:all .2s ease}.oauth-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:1rem;width:1rem;height:1rem}.oauth-btn--cancel[_ngcontent-%COMP%]{background:var(--color-background);color:var(--color-text-secondary)}.oauth-btn--cancel[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover);color:var(--color-text)}.oauth-btn--authorize[_ngcontent-%COMP%]{background:var(--color-primary);color:#fff;border-color:var(--color-primary)}.oauth-btn--authorize[_ngcontent-%COMP%]:hover{opacity:.9}"],changeDetection:0})};var jn=class n{http=h(je);projectState=h(Ye);threadState=h(gt);getBaseUrl(){return`/api/projects/${this.projectState.getSelectedProjectIdOrThrow()}/threads/${this.threadState.getSelectedThreadIdOrThrow()}/files`}uploadFile(e){let t=this.projectState.getSelectedProjectIdOrThrow(),i=this.threadState.getSelectedThreadIdOrThrow();return new rn(o=>{let r=new FileReader;r.onload=()=>{let l=r.result.split(",")[1];this.http.post(`/api/projects/${t}/threads/${i}/upload`,{content:l,mimeType:e.type||"application/octet-stream",filename:e.name}).subscribe({next:u=>{o.next({success:u.success,filename:u.filename}),o.complete()},error:u=>o.error(u)})},r.onerror=()=>o.error(new Error("Failed to read file")),r.readAsDataURL(e)})}listFiles(){return this.http.get(this.getBaseUrl()).pipe($e(e=>e.files))}downloadFile(e){let t=encodeURIComponent(e);return this.http.get(`${this.getBaseUrl()}/${t}`,{responseType:"blob"})}deleteFile(e){let t=encodeURIComponent(e);return this.http.delete(`${this.getBaseUrl()}/${t}`)}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var Ct=class n{fileApi=h(jn);eventStream=h(Mn);filesSignal=Ve([]);isLoadingSignal=Ve(!1);currentProjectSignal=Ve(null);currentThreadSignal=Ve(null);files=mn(()=>this.filesSignal());isLoading=mn(()=>this.isLoadingSignal());fileCount=mn(()=>this.filesSignal().length);constructor(){this.subscribeToFileEvents()}initializeForThread(e,t){this.currentProjectSignal.set(e),this.currentThreadSignal.set(t),this.refreshFileList()}clear(){this.filesSignal.set([]),this.currentProjectSignal.set(null),this.currentThreadSignal.set(null)}refreshFileList(){this.isLoadingSignal.set(!0),this.fileApi.listFiles().subscribe({next:e=>{let t=e.map(i=>Oe(K({},i),{lastModified:new Date(i.lastModified)})).sort((i,o)=>o.lastModified.getTime()-i.lastModified.getTime());this.filesSignal.set(t),this.isLoadingSignal.set(!1)},error:e=>{console.error("[FILE_EXCHANGE_STATE] Error loading files:",e),this.isLoadingSignal.set(!1)}})}uploadFile(e){return L(this,null,function*(){return new Promise(t=>{this.fileApi.uploadFile(e).subscribe({next:()=>{this.refreshFileList(),t({success:!0})},error:i=>{console.error("[FILE_EXCHANGE_STATE] Upload error:",i),t({success:!1,error:i.message||"Upload failed"})}})})})}downloadAllFiles(){let e=this.filesSignal();if(e.length===0){console.warn("[FILE_EXCHANGE_STATE] No files to download");return}e.forEach((t,i)=>{setTimeout(()=>{this.downloadFile(t.filename)},i*300)})}downloadFile(e){this.fileApi.downloadFile(e).subscribe({next:t=>{let i=window.URL.createObjectURL(t),o=document.createElement("a");o.href=i,o.download=e,o.click(),window.URL.revokeObjectURL(i)},error:t=>{console.error("[FILE_EXCHANGE_STATE] Download error:",t)}})}deleteFile(e){return L(this,null,function*(){return new Promise(t=>{this.fileApi.deleteFile(e).subscribe({next:()=>{this.refreshFileList(),t({success:!0})},error:i=>{console.error("[FILE_EXCHANGE_STATE] Delete error:",i),t({success:!1,error:i.message||"Delete failed"})}})})})}subscribeToFileEvents(){this.eventStream.events$.pipe(we(e=>e instanceof Sn),cr()).subscribe(e=>{this.handleFileEvent(e)})}handleFileEvent(e){let t=this.filesSignal();switch(e.operation){case"created":{let i=e.timestamp,o=e.timestamp.lastIndexOf("-");if(o>0){let a=e.timestamp.substring(o+1);a.length===5&&/^[a-z0-9]+$/.test(a)&&(i=e.timestamp.substring(0,o))}let r={filename:e.filename,size:e.size||0,lastModified:new Date(i)};this.filesSignal.set([r,...t]);break}case"updated":{let i=t.filter(u=>u.filename!==e.filename),o=t.find(u=>u.filename===e.filename),r=e.timestamp,a=e.timestamp.lastIndexOf("-");if(a>0){let u=e.timestamp.substring(a+1);u.length===5&&/^[a-z0-9]+$/.test(u)&&(r=e.timestamp.substring(0,a))}let l={filename:e.filename,size:e.size||o?.size||0,lastModified:new Date(r)};this.filesSignal.set([l,...i]);break}case"deleted":{let i=t.filter(o=>o.filename!==e.filename);this.filesSignal.set(i);break}}}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};function jl(n,e){if(n&1&&A(0,"div",1),n&2){let t=m();k("innerHTML",t.renderedContent,ge)}}function Wl(n,e){if(n&1&&A(0,"iframe",2),n&2){let t=m();k("srcdoc",t.content,ge)}}function ql(n,e){if(n&1&&(c(0,"pre",3),f(1),d()),n&2){let t=m();p(),D(t.content)}}var Wn=class n{content="";format="text";renderedContent="";sanitizer=h(Pe);markdownService=h(Re);ngOnChanges(e){(e.content||e.format)&&this.renderContent()}renderContent(){this.format==="markdown"?this.renderMarkdown():this.format==="json"&&this.formatJson()}renderMarkdown(){return L(this,null,function*(){try{let e=yield this.markdownService.parse(this.content);this.renderedContent=this.sanitizer.bypassSecurityTrustHtml(e)}catch(e){console.error("[CONTENT_RENDERER] Error rendering markdown:",e),this.content=this.content}})}formatJson(){try{let e=JSON.parse(this.content);this.content=JSON.stringify(e,null,2)}catch(e){console.error("[CONTENT_RENDERER] Error formatting JSON:",e)}}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-content-renderer"]],inputs:{content:"content",format:"format"},features:[Ie],decls:4,vars:2,consts:[[1,"content-renderer",3,"ngClass"],[1,"markdown-content",3,"innerHTML"],["sandbox","allow-same-origin",1,"html-viewer",3,"srcdoc"],[1,"code-content"]],template:function(t,i){t&1&&(c(0,"div",0),x(1,jl,1,1,"div",1)(2,Wl,1,1,"iframe",2)(3,ql,2,1,"pre",3),d()),t&2&&(k("ngClass","format-"+i.format),p(),_(i.format==="markdown"?1:i.format==="html"?2:3))},dependencies:[_e,hn],styles:[".content-renderer[_ngcontent-%COMP%]{width:100%;height:100%;overflow:auto;padding:1rem}.markdown-content[_ngcontent-%COMP%]{line-height:1.6;color:var(--color-text)}.code-content[_ngcontent-%COMP%]{font-family:Monaco,Menlo,Ubuntu Mono,monospace;font-size:.9rem;line-height:1.5;margin:0;white-space:pre-wrap;word-wrap:break-word;color:var(--color-text)}.format-json[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%]{color:var(--color-code-text, #d63384)}.format-yaml[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%], .format-text[_ngcontent-%COMP%] .code-content[_ngcontent-%COMP%]{color:var(--color-text)}.html-viewer[_ngcontent-%COMP%]{width:100%;height:100%;min-height:400px;border:1px solid var(--color-border);border-radius:8px;background:#fff}"]})};var yt=class n{http=h(je);MAX_FILE_SIZE=20*1024*1024;isViewable(e){return e<=this.MAX_FILE_SIZE}isFormatViewable(e){let t=e.split(".").pop()?.toLowerCase();return!(t&&["pdf","png","jpg","jpeg","gif","webp","zip","tar","gz","exe","bin","doc","docx","xls","xlsx","ppt","pptx"].includes(t))}detectFormat(e){switch(e.split(".").pop()?.toLowerCase()){case"md":return"markdown";case"json":return"json";case"yaml":case"yml":return"yaml";case"html":case"htm":return"html";default:return"text"}}loadFileContent(e,t,i){let o=`/api/projects/${e}/threads/${t}/files/${encodeURIComponent(i)}`,r=this.detectFormat(i);return this.http.get(o,{responseType:"text",observe:"response"}).pipe($e(a=>{let l=a.body||"",u=new Blob([l]).size;return{content:l,format:r,filename:i,size:u}}),sn(a=>(console.error("[CONTENT_VIEWER] Error loading file:",i,a),To(()=>new Error(`Failed to load file: ${a.message||"Unknown error"}`)))))}formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};function Yl(n,e){if(n&1){let t=E();c(0,"button",12),w("click",function(){C(t);let o=m();return y(o.download())}),c(1,"mat-icon"),f(2,"download"),d()()}}function Gl(n,e){n&1&&(c(0,"div",9),A(1,"mat-spinner",13),c(2,"p"),f(3,"Loading file content..."),d()())}function Xl(n,e){if(n&1){let t=E();c(0,"div",10)(1,"mat-icon",14),f(2,"error_outline"),d(),c(3,"p",15),f(4),d(),c(5,"button",16),w("click",function(){C(t);let o=m();return y(o.download())}),c(6,"mat-icon"),f(7,"download"),d(),f(8," Download instead "),d()()}if(n&2){let t=m();p(4),D(t.error)}}function Ql(n,e){if(n&1&&A(0,"app-content-renderer",11),n&2){let t=m();k("content",t.fileContent.content)("format",t.fileContent.format)}}var qn=class n{destroy$=new oe;file;projectName;threadId;closeViewer=new H;contentService=h(yt);eventStream=h(Mn);fileContent=null;isLoading=!1;error="";ngOnInit(){this.loadContent(),this.subscribeToFileEvents()}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete()}loadContent(){if(!this.contentService.isViewable(this.file.size)){this.error=`File too large to view (${this.contentService.formatSize(this.file.size)}). Maximum size: 20 MB.`;return}this.isLoading=!0,this.error="",this.contentService.loadFileContent(this.projectName,this.threadId,this.file.filename).subscribe({next:e=>{console.log("[CONTENT_VIEWER] Content loaded:",e.filename),this.fileContent=e,this.isLoading=!1},error:e=>{console.error("[CONTENT_VIEWER] Error loading content:",e),this.error=e.message||"Failed to load file content",this.isLoading=!1}})}onClose(){this.closeViewer.emit()}download(){let e=new Blob([this.fileContent?.content||""],{type:"text/plain"}),t=window.URL.createObjectURL(e),i=document.createElement("a");i.href=t,i.download=this.file.filename,i.click(),window.URL.revokeObjectURL(t)}formatSize(e){return this.contentService.formatSize(e)}subscribeToFileEvents(){this.eventStream.events$.pipe(we(e=>e instanceof Sn),we(e=>e.filename===this.file.filename),we(e=>e.operation==="updated"),B(this.destroy$)).subscribe(e=>{console.log("[CONTENT_VIEWER] File updated event received, reloading:",e.filename),e.size&&(this.file.size=e.size),this.loadContent()})}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-content-viewer"]],inputs:{file:"file",projectName:"projectName",threadId:"threadId"},outputs:{closeViewer:"closeViewer"},decls:16,vars:6,consts:[[1,"viewer-container"],[1,"viewer-header"],[1,"header-info"],[1,"filename"],[1,"file-size"],[1,"header-actions"],["mat-icon-button","","title","Download","type","button"],["mat-icon-button","","title","Close","type","button",3,"click"],[1,"viewer-content"],[1,"loading-state"],[1,"error-state"],[3,"content","format"],["mat-icon-button","","title","Download","type","button",3,"click"],["diameter","48"],[1,"error-icon"],[1,"error-message"],["mat-raised-button","","color","primary","type","button",3,"click"]],template:function(t,i){t&1&&(c(0,"div",0)(1,"div",1)(2,"div",2)(3,"span",3),f(4),d(),c(5,"span",4),f(6),d()(),c(7,"div",5),x(8,Yl,3,0,"button",6),c(9,"button",7),w("click",function(){return i.onClose()}),c(10,"mat-icon"),f(11,"chevron_right"),d()()()(),c(12,"div",8),x(13,Gl,4,0,"div",9),x(14,Xl,9,1,"div",10),x(15,Ql,1,2,"app-content-renderer",11),d()()),t&2&&(p(4),D(i.file.filename),p(2),D(i.formatSize(i.file.size)),p(2),_(i.fileContent&&!i.isLoading&&!i.error?8:-1),p(5),_(i.isLoading?13:-1),p(),_(i.error?14:-1),p(),_(i.fileContent&&!i.isLoading&&!i.error?15:-1))},dependencies:[_e,he,J,qe,Zo,We,vn,_n,Wn],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%}.viewer-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%;background:var(--color-bg)}.viewer-header[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:1rem;border-bottom:1px solid var(--color-border);background:var(--color-bg);flex-shrink:0}.header-info[_ngcontent-%COMP%]{flex:1;min-width:0;display:flex;flex-direction:column;gap:.25rem}.filename[_ngcontent-%COMP%]{font-weight:500;color:var(--color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file-size[_ngcontent-%COMP%]{font-size:.75rem;color:var(--color-text-secondary)}.header-actions[_ngcontent-%COMP%]{display:flex;gap:.25rem;flex-shrink:0}.viewer-content[_ngcontent-%COMP%]{flex:1;overflow:auto;background:var(--color-bg)}.loading-state[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:1rem;color:var(--color-text-secondary)}.error-state[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:1rem;padding:2rem;text-align:center}.error-icon[_ngcontent-%COMP%]{font-size:3rem;width:3rem;height:3rem;color:var(--color-error)}.error-message[_ngcontent-%COMP%]{color:var(--color-text);margin:0;max-width:400px}"]})};var Zl=Math.pow(10,8)*24*60*60*1e3,gh=-Zl,Yn=6048e5,Xr=864e5;var Kl=3600;var Qr=Kl*24,fh=Qr*7,Jl=Qr*365.2425,ec=Jl/12,bh=ec*3,Gi=Symbol.for("constructDateFrom");function G(n,e){return typeof n=="function"?n(e):n&&typeof n=="object"&&Gi in n?n[Gi](e):n instanceof Date?new n.constructor(e):new Date(e)}function U(n,e){return G(e||n,n)}function Zr(n,e,t){let i=U(n,t?.in);return isNaN(e)?G(t?.in||n,NaN):(e&&i.setDate(i.getDate()+e),i)}var tc={};function Ge(){return tc}function He(n,e){let t=Ge(),i=e?.weekStartsOn??e?.locale?.options?.weekStartsOn??t.weekStartsOn??t.locale?.options?.weekStartsOn??0,o=U(n,e?.in),r=o.getDay(),a=(r<i?7:0)+r-i;return o.setDate(o.getDate()-a),o.setHours(0,0,0,0),o}function it(n,e){return He(n,Oe(K({},e),{weekStartsOn:1}))}function Gn(n,e){let t=U(n,e?.in),i=t.getFullYear(),o=G(t,0);o.setFullYear(i+1,0,4),o.setHours(0,0,0,0);let r=it(o),a=G(t,0);a.setFullYear(i,0,4),a.setHours(0,0,0,0);let l=it(a);return t.getTime()>=r.getTime()?i+1:t.getTime()>=l.getTime()?i:i-1}function Xi(n){let e=U(n),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+n-+t}function wt(n,...e){let t=G.bind(null,n||e.find(i=>typeof i=="object"));return e.map(t)}function Tt(n,e){let t=U(n,e?.in);return t.setHours(0,0,0,0),t}function Xn(n,e,t){let[i,o]=wt(t?.in,n,e),r=Tt(i),a=Tt(o),l=+r-Xi(r),u=+a-Xi(a);return Math.round((l-u)/Xr)}function Kr(n,e){let t=Gn(n,e),i=G(e?.in||n,0);return i.setFullYear(t,0,4),i.setHours(0,0,0,0),it(i)}function Jr(n){return G(n,Date.now())}function ea(n,e,t){let[i,o]=wt(t?.in,n,e);return+Tt(i)==+Tt(o)}function ta(n){return n instanceof Date||typeof n=="object"&&Object.prototype.toString.call(n)==="[object Date]"}function na(n){return!(!ta(n)&&typeof n!="number"||isNaN(+U(n)))}function oa(n,e,t){let[i,o]=wt(t?.in,n,e),r=ia(i,o),a=Math.abs(Xn(i,o));i.setDate(i.getDate()-r*a);let l=+(ia(i,o)===-r),u=r*(a-l);return u===0?0:u}function ia(n,e){let t=n.getFullYear()-e.getFullYear()||n.getMonth()-e.getMonth()||n.getDate()-e.getDate()||n.getHours()-e.getHours()||n.getMinutes()-e.getMinutes()||n.getSeconds()-e.getSeconds()||n.getMilliseconds()-e.getMilliseconds();return t<0?-1:t>0?1:t}function ra(n,e){let t=U(n,e?.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}var nc={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},aa=(n,e,t)=>{let i,o=nc[n];return typeof o=="string"?i=o:e===1?i=o.one:i=o.other.replace("{{count}}",e.toString()),t?.addSuffix?t.comparison&&t.comparison>0?"in "+i:i+" ago":i};function Qn(n){return(e={})=>{let t=e.width?String(e.width):n.defaultWidth;return n.formats[t]||n.formats[n.defaultWidth]}}var ic={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},oc={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},rc={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},sa={date:Qn({formats:ic,defaultWidth:"full"}),time:Qn({formats:oc,defaultWidth:"full"}),dateTime:Qn({formats:rc,defaultWidth:"full"})};var ac={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},la=(n,e,t,i)=>ac[n];function St(n){return(e,t)=>{let i=t?.context?String(t.context):"standalone",o;if(i==="formatting"&&n.formattingValues){let a=n.defaultFormattingWidth||n.defaultWidth,l=t?.width?String(t.width):a;o=n.formattingValues[l]||n.formattingValues[a]}else{let a=n.defaultWidth,l=t?.width?String(t.width):n.defaultWidth;o=n.values[l]||n.values[a]}let r=n.argumentCallback?n.argumentCallback(e):e;return o[r]}}var sc={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},lc={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},cc={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},dc={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},pc={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},mc={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},uc=(n,e)=>{let t=Number(n),i=t%100;if(i>20||i<10)switch(i%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},ca={ordinalNumber:uc,era:St({values:sc,defaultWidth:"wide"}),quarter:St({values:lc,defaultWidth:"wide",argumentCallback:n=>n-1}),month:St({values:cc,defaultWidth:"wide"}),day:St({values:dc,defaultWidth:"wide"}),dayPeriod:St({values:pc,defaultWidth:"wide",formattingValues:mc,defaultFormattingWidth:"wide"})};function kt(n){return(e,t={})=>{let i=t.width,o=i&&n.matchPatterns[i]||n.matchPatterns[n.defaultMatchWidth],r=e.match(o);if(!r)return null;let a=r[0],l=i&&n.parsePatterns[i]||n.parsePatterns[n.defaultParseWidth],u=Array.isArray(l)?gc(l,M=>M.test(a)):hc(l,M=>M.test(a)),b;b=n.valueCallback?n.valueCallback(u):u,b=t.valueCallback?t.valueCallback(b):b;let S=e.slice(a.length);return{value:b,rest:S}}}function hc(n,e){for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&e(n[t]))return t}function gc(n,e){for(let t=0;t<n.length;t++)if(e(n[t]))return t}function da(n){return(e,t={})=>{let i=e.match(n.matchPattern);if(!i)return null;let o=i[0],r=e.match(n.parsePattern);if(!r)return null;let a=n.valueCallback?n.valueCallback(r[0]):r[0];a=t.valueCallback?t.valueCallback(a):a;let l=e.slice(o.length);return{value:a,rest:l}}}var fc=/^(\d+)(th|st|nd|rd)?/i,bc=/\d+/i,xc={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},_c={any:[/^b/i,/^(a|c)/i]},vc={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Cc={any:[/1/i,/2/i,/3/i,/4/i]},yc={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},wc={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},Tc={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},Sc={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},kc={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},Mc={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},pa={ordinalNumber:da({matchPattern:fc,parsePattern:bc,valueCallback:n=>parseInt(n,10)}),era:kt({matchPatterns:xc,defaultMatchWidth:"wide",parsePatterns:_c,defaultParseWidth:"any"}),quarter:kt({matchPatterns:vc,defaultMatchWidth:"wide",parsePatterns:Cc,defaultParseWidth:"any",valueCallback:n=>n+1}),month:kt({matchPatterns:yc,defaultMatchWidth:"wide",parsePatterns:wc,defaultParseWidth:"any"}),day:kt({matchPatterns:Tc,defaultMatchWidth:"wide",parsePatterns:Sc,defaultParseWidth:"any"}),dayPeriod:kt({matchPatterns:kc,defaultMatchWidth:"any",parsePatterns:Mc,defaultParseWidth:"any"})};var Qi={code:"en-US",formatDistance:aa,formatLong:sa,formatRelative:la,localize:ca,match:pa,options:{weekStartsOn:0,firstWeekContainsDate:1}};function ma(n,e){let t=U(n,e?.in);return Xn(t,ra(t))+1}function ua(n,e){let t=U(n,e?.in),i=+it(t)-+Kr(t);return Math.round(i/Yn)+1}function Zn(n,e){let t=U(n,e?.in),i=t.getFullYear(),o=Ge(),r=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??o.firstWeekContainsDate??o.locale?.options?.firstWeekContainsDate??1,a=G(e?.in||n,0);a.setFullYear(i+1,0,r),a.setHours(0,0,0,0);let l=He(a,e),u=G(e?.in||n,0);u.setFullYear(i,0,r),u.setHours(0,0,0,0);let b=He(u,e);return+t>=+l?i+1:+t>=+b?i:i-1}function ha(n,e){let t=Ge(),i=e?.firstWeekContainsDate??e?.locale?.options?.firstWeekContainsDate??t.firstWeekContainsDate??t.locale?.options?.firstWeekContainsDate??1,o=Zn(n,e),r=G(e?.in||n,0);return r.setFullYear(o,0,i),r.setHours(0,0,0,0),He(r,e)}function ga(n,e){let t=U(n,e?.in),i=+He(t,e)-+ha(t,e);return Math.round(i/Yn)+1}function F(n,e){let t=n<0?"-":"",i=Math.abs(n).toString().padStart(e,"0");return t+i}var ze={y(n,e){let t=n.getFullYear(),i=t>0?t:1-t;return F(e==="yy"?i%100:i,e.length)},M(n,e){let t=n.getMonth();return e==="M"?String(t+1):F(t+1,2)},d(n,e){return F(n.getDate(),e.length)},a(n,e){let t=n.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];default:return t==="am"?"a.m.":"p.m."}},h(n,e){return F(n.getHours()%12||12,e.length)},H(n,e){return F(n.getHours(),e.length)},m(n,e){return F(n.getMinutes(),e.length)},s(n,e){return F(n.getSeconds(),e.length)},S(n,e){let t=e.length,i=n.getMilliseconds(),o=Math.trunc(i*Math.pow(10,t-3));return F(o,e.length)}};var Mt={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Zi={G:function(n,e,t){let i=n.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(i,{width:"abbreviated"});case"GGGGG":return t.era(i,{width:"narrow"});default:return t.era(i,{width:"wide"})}},y:function(n,e,t){if(e==="yo"){let i=n.getFullYear(),o=i>0?i:1-i;return t.ordinalNumber(o,{unit:"year"})}return ze.y(n,e)},Y:function(n,e,t,i){let o=Zn(n,i),r=o>0?o:1-o;if(e==="YY"){let a=r%100;return F(a,2)}return e==="Yo"?t.ordinalNumber(r,{unit:"year"}):F(r,e.length)},R:function(n,e){let t=Gn(n);return F(t,e.length)},u:function(n,e){let t=n.getFullYear();return F(t,e.length)},Q:function(n,e,t){let i=Math.ceil((n.getMonth()+1)/3);switch(e){case"Q":return String(i);case"QQ":return F(i,2);case"Qo":return t.ordinalNumber(i,{unit:"quarter"});case"QQQ":return t.quarter(i,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(i,{width:"narrow",context:"formatting"});default:return t.quarter(i,{width:"wide",context:"formatting"})}},q:function(n,e,t){let i=Math.ceil((n.getMonth()+1)/3);switch(e){case"q":return String(i);case"qq":return F(i,2);case"qo":return t.ordinalNumber(i,{unit:"quarter"});case"qqq":return t.quarter(i,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(i,{width:"narrow",context:"standalone"});default:return t.quarter(i,{width:"wide",context:"standalone"})}},M:function(n,e,t){let i=n.getMonth();switch(e){case"M":case"MM":return ze.M(n,e);case"Mo":return t.ordinalNumber(i+1,{unit:"month"});case"MMM":return t.month(i,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(i,{width:"narrow",context:"formatting"});default:return t.month(i,{width:"wide",context:"formatting"})}},L:function(n,e,t){let i=n.getMonth();switch(e){case"L":return String(i+1);case"LL":return F(i+1,2);case"Lo":return t.ordinalNumber(i+1,{unit:"month"});case"LLL":return t.month(i,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(i,{width:"narrow",context:"standalone"});default:return t.month(i,{width:"wide",context:"standalone"})}},w:function(n,e,t,i){let o=ga(n,i);return e==="wo"?t.ordinalNumber(o,{unit:"week"}):F(o,e.length)},I:function(n,e,t){let i=ua(n);return e==="Io"?t.ordinalNumber(i,{unit:"week"}):F(i,e.length)},d:function(n,e,t){return e==="do"?t.ordinalNumber(n.getDate(),{unit:"date"}):ze.d(n,e)},D:function(n,e,t){let i=ma(n);return e==="Do"?t.ordinalNumber(i,{unit:"dayOfYear"}):F(i,e.length)},E:function(n,e,t){let i=n.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(i,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(i,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(i,{width:"short",context:"formatting"});default:return t.day(i,{width:"wide",context:"formatting"})}},e:function(n,e,t,i){let o=n.getDay(),r=(o-i.weekStartsOn+8)%7||7;switch(e){case"e":return String(r);case"ee":return F(r,2);case"eo":return t.ordinalNumber(r,{unit:"day"});case"eee":return t.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(o,{width:"short",context:"formatting"});default:return t.day(o,{width:"wide",context:"formatting"})}},c:function(n,e,t,i){let o=n.getDay(),r=(o-i.weekStartsOn+8)%7||7;switch(e){case"c":return String(r);case"cc":return F(r,e.length);case"co":return t.ordinalNumber(r,{unit:"day"});case"ccc":return t.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(o,{width:"narrow",context:"standalone"});case"cccccc":return t.day(o,{width:"short",context:"standalone"});default:return t.day(o,{width:"wide",context:"standalone"})}},i:function(n,e,t){let i=n.getDay(),o=i===0?7:i;switch(e){case"i":return String(o);case"ii":return F(o,e.length);case"io":return t.ordinalNumber(o,{unit:"day"});case"iii":return t.day(i,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(i,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(i,{width:"short",context:"formatting"});default:return t.day(i,{width:"wide",context:"formatting"})}},a:function(n,e,t){let o=n.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(n,e,t){let i=n.getHours(),o;switch(i===12?o=Mt.noon:i===0?o=Mt.midnight:o=i/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(n,e,t){let i=n.getHours(),o;switch(i>=17?o=Mt.evening:i>=12?o=Mt.afternoon:i>=4?o=Mt.morning:o=Mt.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(o,{width:"narrow",context:"formatting"});default:return t.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(n,e,t){if(e==="ho"){let i=n.getHours()%12;return i===0&&(i=12),t.ordinalNumber(i,{unit:"hour"})}return ze.h(n,e)},H:function(n,e,t){return e==="Ho"?t.ordinalNumber(n.getHours(),{unit:"hour"}):ze.H(n,e)},K:function(n,e,t){let i=n.getHours()%12;return e==="Ko"?t.ordinalNumber(i,{unit:"hour"}):F(i,e.length)},k:function(n,e,t){let i=n.getHours();return i===0&&(i=24),e==="ko"?t.ordinalNumber(i,{unit:"hour"}):F(i,e.length)},m:function(n,e,t){return e==="mo"?t.ordinalNumber(n.getMinutes(),{unit:"minute"}):ze.m(n,e)},s:function(n,e,t){return e==="so"?t.ordinalNumber(n.getSeconds(),{unit:"second"}):ze.s(n,e)},S:function(n,e){return ze.S(n,e)},X:function(n,e,t){let i=n.getTimezoneOffset();if(i===0)return"Z";switch(e){case"X":return ba(i);case"XXXX":case"XX":return ot(i);default:return ot(i,":")}},x:function(n,e,t){let i=n.getTimezoneOffset();switch(e){case"x":return ba(i);case"xxxx":case"xx":return ot(i);default:return ot(i,":")}},O:function(n,e,t){let i=n.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+fa(i,":");default:return"GMT"+ot(i,":")}},z:function(n,e,t){let i=n.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+fa(i,":");default:return"GMT"+ot(i,":")}},t:function(n,e,t){let i=Math.trunc(+n/1e3);return F(i,e.length)},T:function(n,e,t){return F(+n,e.length)}};function fa(n,e=""){let t=n>0?"-":"+",i=Math.abs(n),o=Math.trunc(i/60),r=i%60;return r===0?t+String(o):t+String(o)+e+F(r,2)}function ba(n,e){return n%60===0?(n>0?"-":"+")+F(Math.abs(n)/60,2):ot(n,e)}function ot(n,e=""){let t=n>0?"-":"+",i=Math.abs(n),o=F(Math.trunc(i/60),2),r=F(i%60,2);return t+o+e+r}var xa=(n,e)=>{switch(n){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});default:return e.date({width:"full"})}},_a=(n,e)=>{switch(n){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});default:return e.time({width:"full"})}},Ec=(n,e)=>{let t=n.match(/(P+)(p+)?/)||[],i=t[1],o=t[2];if(!o)return xa(n,e);let r;switch(i){case"P":r=e.dateTime({width:"short"});break;case"PP":r=e.dateTime({width:"medium"});break;case"PPP":r=e.dateTime({width:"long"});break;default:r=e.dateTime({width:"full"});break}return r.replace("{{date}}",xa(i,e)).replace("{{time}}",_a(o,e))},va={p:_a,P:Ec};var Oc=/^D+$/,Ic=/^Y+$/,Pc=["D","DD","YY","YYYY"];function Ca(n){return Oc.test(n)}function ya(n){return Ic.test(n)}function wa(n,e,t){let i=Ac(n,e,t);if(console.warn(i),Pc.includes(n))throw new RangeError(i)}function Ac(n,e,t){let i=n[0]==="Y"?"years":"days of the month";return`Use \`${n.toLowerCase()}\` instead of \`${n}\` (in \`${e}\`) for formatting ${i} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}var Dc=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Rc=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Fc=/^'([^]*?)'?$/,Nc=/''/g,Lc=/[a-zA-Z]/;function Ki(n,e,t){let i=Ge(),o=t?.locale??i.locale??Qi,r=t?.firstWeekContainsDate??t?.locale?.options?.firstWeekContainsDate??i.firstWeekContainsDate??i.locale?.options?.firstWeekContainsDate??1,a=t?.weekStartsOn??t?.locale?.options?.weekStartsOn??i.weekStartsOn??i.locale?.options?.weekStartsOn??0,l=U(n,t?.in);if(!na(l))throw new RangeError("Invalid time value");let u=e.match(Rc).map(S=>{let M=S[0];if(M==="p"||M==="P"){let I=va[M];return I(S,o.formatLong)}return S}).join("").match(Dc).map(S=>{if(S==="''")return{isToken:!1,value:"'"};let M=S[0];if(M==="'")return{isToken:!1,value:Hc(S)};if(Zi[M])return{isToken:!0,value:S};if(M.match(Lc))throw new RangeError("Format string contains an unescaped latin alphabet character `"+M+"`");return{isToken:!1,value:S}});o.localize.preprocessor&&(u=o.localize.preprocessor(l,u));let b={firstWeekContainsDate:r,weekStartsOn:a,locale:o};return u.map(S=>{if(!S.isToken)return S.value;let M=S.value;(!t?.useAdditionalWeekYearTokens&&ya(M)||!t?.useAdditionalDayOfYearTokens&&Ca(M))&&wa(M,e,String(n));let I=Zi[M[0]];return I(l,M,o.localize,b)}).join("")}function Hc(n){let e=n.match(Fc);return e?e[1].replace(Nc,"'"):n}function Ta(n,e,t){return Zr(n,-e,t)}function Sa(n,e){return ea(G(e?.in||n,n),Ta(Jr(e?.in||n),1))}function ka(n){if(!n||isNaN(n.getTime()))return"unknown";let e=new Date,t=Ki(n,"HH:mm:ss"),i=e.getTime()-n.getTime(),o=Math.floor(i/(1e3*60));if(o<1)return`just now (${t})`;if(o<60)return`${o} min ago (${t})`;let r=Math.floor(i/(1e3*60*60));if(r<24)return`${r}h ago (${t})`;if(Sa(n))return`yesterday ${t}`;let a=oa(e,n);return a<7?`${a}d ago ${t}`:`${Ki(n,"dd/MM/yyyy")} ${t}`}var zc=(n,e)=>e.filename;function $c(n,e){if(n&1){let t=E();c(0,"button",11),w("click",function(){C(t);let o=m(2);return y(o.downloadAll())}),c(1,"mat-icon"),f(2,"download_for_offline"),d()()}}function Vc(n,e){n&1&&(c(0,"div",10),A(1,"span",12),c(2,"span",13),f(3,"Loading files..."),d()())}function Uc(n,e){n&1&&(c(0,"div",14)(1,"mat-icon",15),f(2,"folder_open"),d(),c(3,"p",16),f(4,"No files in exchange space"),d(),c(5,"p",17),f(6,"Upload files to share with the agent"),d()())}function Bc(n,e){if(n&1){let t=E();c(0,"button",28),w("click",function(){C(t);let o=m().$implicit,r=m(4);return y(r.viewFile(o))}),c(1,"mat-icon"),f(2,"visibility"),d()()}}function jc(n,e){if(n&1){let t=E();c(0,"div",18)(1,"div",19)(2,"mat-icon",20),f(3),d(),c(4,"div",21)(5,"span",22),f(6),d(),c(7,"span",23),f(8),d()()(),c(9,"div",24),x(10,Bc,3,0,"button",25),c(11,"button",26),w("click",function(){let o=C(t).$implicit,r=m(4);return y(r.download(o))}),c(12,"mat-icon"),f(13,"download"),d()(),c(14,"button",27),w("click",function(){let o=C(t).$implicit,r=m(4);return y(r.delete(o))}),c(15,"mat-icon"),f(16,"delete"),d()()()()}if(n&2){let t=e.$implicit,i=m(4);p(3),D(i.getFileIcon(t.filename)),p(2),k("title",t.filename),p(),D(t.filename),p(2),ln("",i.formatSize(t.size)," \u2022 ",i.formatDate(t.lastModified)),p(2),_(i.canViewFile(t)?10:-1)}}function Wc(n,e){if(n&1&&me(0,jc,17,6,"div",18,zc),n&2){let t=m(3);ue(t.files())}}function qc(n,e){if(n&1&&x(0,Uc,7,0,"div",14)(1,Wc,2,0),n&2){let t=m(2);_(t.files().length===0?0:1)}}function Yc(n,e){if(n&1){let t=E();c(0,"div",0)(1,"div",2)(2,"div",3)(3,"h3",4),f(4,"Exchange"),d(),c(5,"span",5),f(6),d()(),c(7,"div",6),x(8,$c,3,0,"button",7),c(9,"button",8),w("click",function(){C(t);let o=m();return y(o.close())}),c(10,"mat-icon"),f(11,"chevron_right"),d()()()(),c(12,"div",9),x(13,Vc,4,0,"div",10)(14,qc,2,1),d()()}if(n&2){let t=m();p(6),ut("(",t.files().length,")"),p(2),_(t.files().length>0?8:-1),p(5),_(t.isLoading()?13:14)}}function Gc(n,e){if(n&1){let t=E();c(0,"app-content-viewer",29),w("closeViewer",function(){C(t);let o=m();return y(o.backToList())}),d()}if(n&2){let t=m();k("file",t.currentFile)("projectName",t.projectName)("threadId",t.threadId)}}var Kn=class n{projectName;threadId;closeDrawer=new H;fileExchangeState=h(Ct);contentViewerService=h(yt);files=this.fileExchangeState.files;isLoading=this.fileExchangeState.isLoading;viewerState="list";currentFile=null;close(){this.viewerState==="content"?this.backToList():this.closeDrawer.emit()}viewFile(e){this.currentFile=e,this.viewerState="content"}backToList(){this.viewerState="list",this.currentFile=null}downloadAll(){this.fileExchangeState.downloadAllFiles()}download(e){this.fileExchangeState.downloadFile(e.filename)}delete(e){return L(this,null,function*(){if(!confirm(`Delete file "${e.filename}"?`))return;let i=yield this.fileExchangeState.deleteFile(e.filename);i.success||alert(`Failed to delete file: ${i.error}`)})}getFileIcon(e){switch(e.split(".").pop()?.toLowerCase()){case"pdf":return"picture_as_pdf";case"csv":case"xlsx":case"xls":return"table_chart";case"txt":case"md":return"description";case"jpg":case"jpeg":case"png":case"gif":case"webp":return"image";case"zip":case"tar":case"gz":return"folder_zip";default:return"insert_drive_file"}}formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}formatDate(e){return ka(e)}canViewFile(e){return this.contentViewerService.isFormatViewable(e.filename)&&this.contentViewerService.isViewable(e.size)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-file-exchange-drawer"]],inputs:{projectName:"projectName",threadId:"threadId"},outputs:{closeDrawer:"closeDrawer"},decls:2,vars:2,consts:[[1,"file-drawer-container"],[3,"file","projectName","threadId"],[1,"drawer-header"],[1,"header-left"],[1,"drawer-title"],[1,"file-count"],[1,"header-actions"],["mat-icon-button","","title","Download all files","type","button",1,"download-all-btn"],["mat-icon-button","","title","Close","type","button",1,"close-btn",3,"click"],[1,"file-list"],[1,"file-loading"],["mat-icon-button","","title","Download all files","type","button",1,"download-all-btn",3,"click"],[1,"loading-spinner"],[1,"loading-text"],[1,"file-empty"],[1,"empty-icon"],[1,"empty-text"],[1,"empty-hint"],[1,"file-item"],[1,"file-info"],[1,"file-icon"],[1,"file-details"],[1,"file-name",3,"title"],[1,"file-meta"],[1,"file-actions"],["mat-icon-button","","title","View","type","button",1,"action-btn","view-btn"],["mat-icon-button","","title","Download","type","button",1,"action-btn","download-btn",3,"click"],["mat-icon-button","","title","Delete","type","button",1,"action-btn","delete-btn",3,"click"],["mat-icon-button","","title","View","type","button",1,"action-btn","view-btn",3,"click"],[3,"closeViewer","file","projectName","threadId"]],template:function(t,i){t&1&&(x(0,Yc,15,3,"div",0),x(1,Gc,1,3,"app-content-viewer",1)),t&2&&(_(i.viewerState==="list"?0:-1),p(),_(i.viewerState==="content"&&i.currentFile?1:-1))},dependencies:[_e,he,J,qe,We,qn],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%}.file-drawer-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;height:100%;background:var(--glass-bg);backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);color:var(--color-text)}.drawer-header[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:1rem;border-bottom:1px solid var(--color-border);flex-shrink:0}.header-left[_ngcontent-%COMP%]{display:flex;align-items:baseline;gap:.5rem}.header-actions[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.25rem}.drawer-title[_ngcontent-%COMP%]{margin:0;font-size:1.25rem;font-weight:600;color:var(--color-text)}.file-count[_ngcontent-%COMP%]{font-size:.9rem;color:var(--color-text-secondary)}.download-all-btn[_ngcontent-%COMP%]{color:var(--color-primary)}.download-all-btn[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.close-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.close-btn[_ngcontent-%COMP%]:hover{color:var(--color-text);background:var(--color-bg-hover)}.file-list[_ngcontent-%COMP%]{flex:1;overflow-y:auto;padding:.5rem}.file-loading[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem 1rem;gap:1rem;color:var(--color-text-secondary)}.loading-spinner[_ngcontent-%COMP%]{display:inline-block;width:32px;height:32px;border:3px solid var(--color-border);border-top-color:var(--color-primary);border-radius:50%;animation:_ngcontent-%COMP%_spin .8s linear infinite}@keyframes _ngcontent-%COMP%_spin{to{transform:rotate(360deg)}}.loading-text[_ngcontent-%COMP%]{font-size:.9rem}.file-empty[_ngcontent-%COMP%]{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:3rem 1rem;text-align:center;color:var(--color-text-secondary)}.empty-icon[_ngcontent-%COMP%]{font-size:64px;width:64px;height:64px;margin-bottom:1rem;opacity:.5}.empty-text[_ngcontent-%COMP%]{margin:0 0 .5rem;font-size:1rem;font-weight:500}.empty-hint[_ngcontent-%COMP%]{margin:0;font-size:.85rem;opacity:.7}.file-item[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:.75rem;border-radius:8px;transition:background .2s;gap:1rem}.file-item[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.file-item[_ngcontent-%COMP%]:hover .file-actions[_ngcontent-%COMP%]{opacity:1}.file-info[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.75rem;flex:1;min-width:0}.file-icon[_ngcontent-%COMP%]{flex-shrink:0;color:var(--color-primary);font-size:28px;width:28px;height:28px}.file-details[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.25rem;min-width:0}.file-name[_ngcontent-%COMP%]{font-weight:500;color:var(--color-text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.file-meta[_ngcontent-%COMP%]{font-size:.8rem;color:var(--color-text-secondary)}.file-actions[_ngcontent-%COMP%]{display:flex;gap:.25rem;flex-shrink:0;opacity:0;transition:opacity .2s}.action-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.action-btn[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.action-btn.view-btn[_ngcontent-%COMP%]:hover, .action-btn.download-btn[_ngcontent-%COMP%]:hover{color:var(--color-primary)}.action-btn.delete-btn[_ngcontent-%COMP%]:hover{color:var(--color-error)}@media(max-width:768px){.file-actions[_ngcontent-%COMP%]{opacity:1}.file-item[_ngcontent-%COMP%]{padding:1rem .75rem}.drawer-header[_ngcontent-%COMP%]{padding:.75rem;padding-top:calc(.75rem + env(safe-area-inset-top,0px))}}"]})};var Jn=class n{http=h(je);listUsers(){return this.http.get("/api/users")}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var ei=class n{excludedUserIds=[];placeholder="Search username";disabled=!1;userSelected=new H;userApi=h(Jn);search(e){let t=e.toLowerCase();return this.userApi.listUsers().pipe($e(i=>i.filter(o=>!this.excludedUserIds.includes(o.username)).filter(o=>o.username.toLowerCase().includes(t)).map(o=>({id:o.username,name:o.username}))))}onItemSelected(e){this.userSelected.emit(e.id)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-user-autocomplete"]],inputs:{excludedUserIds:"excludedUserIds",placeholder:"placeholder",disabled:"disabled"},outputs:{userSelected:"userSelected"},decls:1,vars:3,consts:[[3,"itemSelected","dataSource","placeholder","disabled"]],template:function(t,i){t&1&&(c(0,"ds-autocomplete-input",0),w("itemSelected",function(r){return i.onItemSelected(r)}),d()),t&2&&k("dataSource",i)("placeholder",i.placeholder)("disabled",i.disabled)},dependencies:[gr],styles:["[_nghost-%COMP%]{display:block}"]})};var Xc=(n,e)=>e.userId;function Qc(n,e){if(n&1&&(c(0,"div",7),f(1),d()),n&2){let t=m();p(),D(t.errorMessage())}}function Zc(n,e){if(n&1){let t=E();c(0,"button",13),w("click",function(){C(t);let o=m().$implicit,r=m();return y(r.removeUser(o.userId))}),c(1,"mat-icon"),f(2,"close"),d()()}}function Kc(n,e){if(n&1&&(c(0,"div",9)(1,"mat-icon",10),f(2,"person"),d(),c(3,"span",11),f(4),d(),x(5,Zc,3,0,"button",12),d()),n&2){let t=e.$implicit,i=m();p(4),D(t.userId),p(),_(i.users.length>1?5:-1)}}var Gt=class n{threadId;users=[];currentUsername;userAdded=new H;userRemoved=new H;closed=new H;isAdding=Ve(!1);errorMessage=Ve("");get excludedUserIds(){return[this.currentUsername,...this.users.map(e=>e.userId)]}setAdding(e){this.isAdding.set(e)}setError(e){this.errorMessage.set(e),this.isAdding.set(!1)}onUserSelected(e){this.errorMessage.set(""),this.userAdded.emit(e)}removeUser(e){this.userRemoved.emit(e)}close(){this.closed.emit()}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-thread-share"]],inputs:{threadId:"threadId",users:"users",currentUsername:"currentUsername"},outputs:{userAdded:"userAdded",userRemoved:"userRemoved",closed:"closed"},decls:19,vars:3,consts:[[1,"thread-share"],[1,"share-header"],[1,"header-left"],["mat-icon-button","","title","Close","type","button",1,"close-btn",3,"click"],[1,"share-subheader"],[1,"add-user-section"],[3,"userSelected","excludedUserIds","disabled"],[1,"error-message"],[1,"users-list"],[1,"user-item"],[1,"user-icon"],[1,"user-name"],["mat-icon-button","","title","Remove user",1,"remove-button"],["mat-icon-button","","title","Remove user",1,"remove-button",3,"click"]],template:function(t,i){t&1&&(c(0,"div",0)(1,"div",1)(2,"div",2)(3,"mat-icon"),f(4,"group"),d(),c(5,"span"),f(6,"Share"),d()(),c(7,"button",3),w("click",function(){return i.close()}),c(8,"mat-icon"),f(9,"chevron_right"),d()()(),c(10,"div",4)(11,"span"),f(12,"Participants"),d()(),c(13,"div",5)(14,"app-user-autocomplete",6),w("userSelected",function(r){return i.onUserSelected(r)}),d()(),x(15,Qc,2,1,"div",7),c(16,"div",8),me(17,Kc,6,2,"div",9,Xc),d()()),t&2&&(p(14),k("excludedUserIds",i.excludedUserIds)("disabled",i.isAdding()),p(),_(i.errorMessage()?15:-1),p(2),ue(i.users))},dependencies:[he,J,qe,We,Jo,ei],styles:["[_nghost-%COMP%]{display:flex;flex-direction:column;height:100%}.thread-share[_ngcontent-%COMP%]{display:flex;flex-direction:column;flex:1;min-height:0;background:var(--glass-bg);backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);color:var(--color-text)}.share-header[_ngcontent-%COMP%]{display:flex;align-items:center;justify-content:space-between;padding:1rem;padding-top:calc(1rem + env(safe-area-inset-top,0px));border-bottom:1px solid var(--color-border);flex-shrink:0}.share-header[_ngcontent-%COMP%] .header-left[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;font-weight:600;font-size:1.1rem;color:var(--color-text)}.share-header[_ngcontent-%COMP%] .header-left[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px;color:var(--color-text-secondary)}.share-header[_ngcontent-%COMP%] .close-btn[_ngcontent-%COMP%]{color:var(--color-text-secondary)}.share-header[_ngcontent-%COMP%] .close-btn[_ngcontent-%COMP%]:hover{color:var(--color-text);background:var(--color-bg-hover)}.share-subheader[_ngcontent-%COMP%]{padding:.75rem 1rem .25rem;font-size:.75rem;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--color-text-secondary)}.add-user-section[_ngcontent-%COMP%]{display:flex;align-items:center;padding:0 1rem .75rem;width:50%}.error-message[_ngcontent-%COMP%]{color:var(--color-error);font-size:.75rem;margin-top:-.5rem;padding:0 1rem}.users-list[_ngcontent-%COMP%]{display:flex;flex-direction:column;gap:.25rem;padding:.25rem}.user-item[_ngcontent-%COMP%]{display:flex;align-items:center;gap:.5rem;padding:.5rem .75rem;border-radius:6px;transition:background .15s ease}.user-item[_ngcontent-%COMP%]:hover{background:var(--color-bg-hover)}.user-icon[_ngcontent-%COMP%]{font-size:18px;width:18px;height:18px;color:var(--color-text-secondary);flex-shrink:0}.user-name[_ngcontent-%COMP%]{flex:1;font-size:.875rem;color:var(--color-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.remove-button[_ngcontent-%COMP%]{flex-shrink:0;width:28px!important;height:28px!important;padding:0!important}.remove-button[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:16px;width:16px;height:16px;color:var(--color-text-secondary)}.remove-button[_ngcontent-%COMP%]:hover mat-icon[_ngcontent-%COMP%]{color:var(--color-error, #ef4444)}"]})};var Ma="mat-badge-content",Jc=(()=>{class n{static \u0275fac=function(i){return new(i||n)};static \u0275cmp=P({type:n,selectors:[["ng-component"]],decls:0,vars:0,template:function(i,o){},styles:[`.mat-badge{position:relative}.mat-badge.mat-badge{overflow:visible}.mat-badge-content{position:absolute;text-align:center;display:inline-block;transition:transform 200ms ease-in-out;transform:scale(0.6);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;box-sizing:border-box;pointer-events:none;background-color:var(--mat-badge-background-color, var(--mat-sys-error));color:var(--mat-badge-text-color, var(--mat-sys-on-error));font-family:var(--mat-badge-text-font, var(--mat-sys-label-small-font));font-weight:var(--mat-badge-text-weight, var(--mat-sys-label-small-weight));border-radius:var(--mat-badge-container-shape, var(--mat-sys-corner-full))}.mat-badge-above .mat-badge-content{bottom:100%}.mat-badge-below .mat-badge-content{top:100%}.mat-badge-before .mat-badge-content{right:100%}[dir=rtl] .mat-badge-before .mat-badge-content{right:auto;left:100%}.mat-badge-after .mat-badge-content{left:100%}[dir=rtl] .mat-badge-after .mat-badge-content{left:auto;right:100%}@media(forced-colors: active){.mat-badge-content{outline:solid 1px;border-radius:0}}.mat-badge-disabled .mat-badge-content{background-color:var(--mat-badge-disabled-state-background-color, color-mix(in srgb, var(--mat-sys-error) 38%, transparent));color:var(--mat-badge-disabled-state-text-color, var(--mat-sys-on-error))}.mat-badge-hidden .mat-badge-content{display:none}.ng-animate-disabled .mat-badge-content,.mat-badge-content._mat-animation-noopable{transition:none}.mat-badge-content.mat-badge-active{transform:none}.mat-badge-small .mat-badge-content{width:var(--mat-badge-legacy-small-size-container-size, unset);height:var(--mat-badge-legacy-small-size-container-size, unset);min-width:var(--mat-badge-small-size-container-size, 6px);min-height:var(--mat-badge-small-size-container-size, 6px);line-height:var(--mat-badge-small-size-line-height, 6px);padding:var(--mat-badge-small-size-container-padding, 0);font-size:var(--mat-badge-small-size-text-size, 0);margin:var(--mat-badge-small-size-container-offset, -6px 0)}.mat-badge-small.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-small-size-container-overlap-offset, -6px)}.mat-badge-medium .mat-badge-content{width:var(--mat-badge-legacy-container-size, unset);height:var(--mat-badge-legacy-container-size, unset);min-width:var(--mat-badge-container-size, 16px);min-height:var(--mat-badge-container-size, 16px);line-height:var(--mat-badge-line-height, 16px);padding:var(--mat-badge-container-padding, 0 4px);font-size:var(--mat-badge-text-size, var(--mat-sys-label-small-size));margin:var(--mat-badge-container-offset, -12px 0)}.mat-badge-medium.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-container-overlap-offset, -12px)}.mat-badge-large .mat-badge-content{width:var(--mat-badge-legacy-large-size-container-size, unset);height:var(--mat-badge-legacy-large-size-container-size, unset);min-width:var(--mat-badge-large-size-container-size, 16px);min-height:var(--mat-badge-large-size-container-size, 16px);line-height:var(--mat-badge-large-size-line-height, 16px);padding:var(--mat-badge-large-size-container-padding, 0 4px);font-size:var(--mat-badge-large-size-text-size, var(--mat-sys-label-small-size));margin:var(--mat-badge-large-size-container-offset, -12px 0)}.mat-badge-large.mat-badge-overlap .mat-badge-content{margin:var(--mat-badge-large-size-container-overlap-offset, -12px)}
|
|
83
|
+
`],encapsulation:2,changeDetection:0})}return n})(),Ea=(()=>{class n{_ngZone=h(Eo);_elementRef=h(mt);_ariaDescriber=h(Go);_renderer=h(Po);_animationsDisabled=Qo();_idGenerator=h(Yo);get color(){return this._color}set color(t){this._setColor(t),this._color=t}_color="primary";overlap=!0;disabled=!1;position="above after";get content(){return this._content}set content(t){this._updateRenderedContent(t)}_content;get description(){return this._description}set description(t){this._updateDescription(t)}_description;size="medium";hidden=!1;_badgeElement;_inlineBadgeDescription;_isInitialized=!1;_interactivityChecker=h(Wo);_document=h(Mo);constructor(){let t=h(Bo);t.load(Jc),t.load(jo)}isAbove(){return this.position.indexOf("below")===-1}isAfter(){return this.position.indexOf("before")===-1}getBadgeElement(){return this._badgeElement}ngOnInit(){this._clearExistingBadges(),this.content&&!this._badgeElement&&(this._badgeElement=this._createBadgeElement(),this._updateRenderedContent(this.content)),this._isInitialized=!0}ngAfterViewInit(){}ngOnDestroy(){this._renderer.destroyNode&&(this._renderer.destroyNode(this._badgeElement),this._inlineBadgeDescription?.remove()),this._ariaDescriber.removeDescription(this._elementRef.nativeElement,this.description)}_isHostInteractive(){return this._interactivityChecker.isFocusable(this._elementRef.nativeElement,{ignoreVisibility:!0})}_createBadgeElement(){let t=this._renderer.createElement("span"),i="mat-badge-active";return t.setAttribute("id",this._idGenerator.getId("mat-badge-content-")),t.setAttribute("aria-hidden","true"),t.classList.add(Ma),this._animationsDisabled&&t.classList.add("_mat-animation-noopable"),this._elementRef.nativeElement.appendChild(t),typeof requestAnimationFrame=="function"&&!this._animationsDisabled?this._ngZone.runOutsideAngular(()=>{requestAnimationFrame(()=>{t.classList.add(i)})}):t.classList.add(i),t}_updateRenderedContent(t){let i=`${t??""}`.trim();this._isInitialized&&i&&!this._badgeElement&&(this._badgeElement=this._createBadgeElement()),this._badgeElement&&(this._badgeElement.textContent=i),this._content=i}_updateDescription(t){this._ariaDescriber.removeDescription(this._elementRef.nativeElement,this.description),(!t||this._isHostInteractive())&&this._removeInlineDescription(),this._description=t,this._isHostInteractive()?this._ariaDescriber.describe(this._elementRef.nativeElement,t):this._updateInlineDescription()}_updateInlineDescription(){this._inlineBadgeDescription||(this._inlineBadgeDescription=this._document.createElement("span"),this._inlineBadgeDescription.classList.add("cdk-visually-hidden")),this._inlineBadgeDescription.textContent=this.description,this._badgeElement?.appendChild(this._inlineBadgeDescription)}_removeInlineDescription(){this._inlineBadgeDescription?.remove(),this._inlineBadgeDescription=void 0}_setColor(t){let i=this._elementRef.nativeElement.classList;i.remove(`mat-badge-${this._color}`),t&&i.add(`mat-badge-${t}`)}_clearExistingBadges(){let t=this._elementRef.nativeElement.querySelectorAll(`:scope > .${Ma}`);for(let i of Array.from(t))i!==this._badgeElement&&i.remove()}static \u0275fac=function(i){return new(i||n)};static \u0275dir=Do({type:n,selectors:[["","matBadge",""]],hostAttrs:[1,"mat-badge"],hostVars:20,hostBindings:function(i,o){i&2&&fe("mat-badge-overlap",o.overlap)("mat-badge-above",o.isAbove())("mat-badge-below",!o.isAbove())("mat-badge-before",!o.isAfter())("mat-badge-after",o.isAfter())("mat-badge-small",o.size==="small")("mat-badge-medium",o.size==="medium")("mat-badge-large",o.size==="large")("mat-badge-hidden",o.hidden||!o.content)("mat-badge-disabled",o.disabled)},inputs:{color:[0,"matBadgeColor","color"],overlap:[2,"matBadgeOverlap","overlap",un],disabled:[2,"matBadgeDisabled","disabled",un],position:[0,"matBadgePosition","position"],content:[0,"matBadge","content"],description:[0,"matBadgeDescription","description"],size:[0,"matBadgeSize","size"],hidden:[2,"matBadgeHidden","hidden",un]}})}return n})(),Oa=(()=>{class n{static \u0275fac=function(i){return new(i||n)};static \u0275mod=Ao({type:n});static \u0275inj=ko({imports:[qo,Xo]})}return n})();var Et=class n{ATTENTION_EMOJI="\u{1F534}";isSystemActive=!1;systemActiveTimer=null;SYSTEM_ACTIVE_TIMEOUT=4e3;unreadService=h(vt);project=h(Ye);constructor(){this.initializeTitleUpdates()}initializeTitleUpdates(){So([this.project.selectedProject$,this.unreadService.unreadCount$]).subscribe(([e,t])=>{this.updateTitle(e?.name??"...",t)})}updateTitle(e,t){let i;this.isSystemActive?i=`\u23F3${t>0?` (${t}) `:" "}${e}`:t>0?i=`${this.ATTENTION_EMOJI} (${t}) ${e}`:i=e,document.title=i,console.log("[TAB-TITLE] Updated to:",i)}setSystemActive(){console.log("[TAB-TITLE] System active - showing hourglass"),this.isSystemActive=!0,this.systemActiveTimer&&clearTimeout(this.systemActiveTimer),this.systemActiveTimer=setTimeout(()=>{console.log("[TAB-TITLE] System active timeout - hiding hourglass"),this.isSystemActive=!1,this.forceUpdateTitle()},this.SYSTEM_ACTIVE_TIMEOUT),this.forceUpdateTitle()}setSystemInactive(){console.log("[TAB-TITLE] System inactive - hiding hourglass"),this.isSystemActive=!1,this.systemActiveTimer&&(clearTimeout(this.systemActiveTimer),this.systemActiveTimer=null),this.forceUpdateTitle()}forceUpdateTitle(){let e=this.project.getSelectedProjectId()??"...",t=this.unreadService.getCurrentCount();this.updateTitle(e,t)}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var ti=class n{http=h(je);maxFileSize=5*1024*1024;supportedTypes=["image/png","image/jpeg","image/gif","image/webp"];validateFile(e){if(!this.supportedTypes.includes(e.type))throw new Error(`Unsupported file type: ${e.type}`);if(e.size>this.maxFileSize)throw new Error(`File too large: ${(e.size/1024/1024).toFixed(1)}MB exceeds 5MB limit`)}fileToBase64(e){return L(this,null,function*(){return new Promise((t,i)=>{let o=new FileReader;o.onload=()=>{let r=o.result;if(!r){i(new Error("Failed to read file"));return}let a=r.split(",")[1];if(!a){i(new Error("Invalid file format"));return}t(a)},o.onerror=i,o.readAsDataURL(e)})})}getUploadUrl(e,t){return`/api/projects/${e}/threads/${t}/upload`}uploadImage(e,t,i){console.log("[IMAGE-UPLOAD] uploadImage - file:",e.name,e.type,e.size),console.log("[IMAGE-UPLOAD] uploadImage - project:",t,"thread:",i);try{console.log("[IMAGE-UPLOAD] Validating file..."),this.validateFile(e)}catch(o){return console.log("[IMAGE-UPLOAD] Validation failed:",o),vi({success:!1,error:o instanceof Error?o.message:"Validation failed"})}return new rn(o=>{console.log("[IMAGE-UPLOAD] Converting to base64..."),this.fileToBase64(e).then(r=>{console.log("[IMAGE-UPLOAD] Base64 length:",r.length),console.log("[IMAGE-UPLOAD] Sending upload request..."),this.http.post(this.getUploadUrl(t,i),{content:r,mimeType:e.type,filename:e.name}).pipe($e(a=>(console.log("[IMAGE-UPLOAD] Upload success result:",a),{success:!0,processedSize:a.processedSize,dimensions:a.dimensions})),sn(a=>{console.log("[IMAGE-UPLOAD] Upload failed:",a);let l=a.error?.error||a.message||"Upload failed";return vi({success:!1,error:l})})).subscribe({next:a=>{o.next(a),o.complete()},error:a=>o.error(a)})}).catch(r=>{console.log("[IMAGE-UPLOAD] Base64 conversion failed:",r),o.next({success:!1,error:r instanceof Error?r.message:"Failed to read file"}),o.complete()})})}hasImageFiles(e){if(console.log("[IMAGE-UPLOAD] hasImageFiles - dataTransfer:",e),!e)return console.log("[IMAGE-UPLOAD] hasImageFiles - no dataTransfer"),!1;if(console.log("[IMAGE-UPLOAD] hasImageFiles - types:",Array.from(e.types)),!Array.from(e.types).includes("Files"))return console.log("[IMAGE-UPLOAD] hasImageFiles - no Files type"),!1;let t=Array.from(e.files||[]);console.log("[IMAGE-UPLOAD] hasImageFiles - files:",t.map(o=>({name:o.name,type:o.type})));let i=t.some(o=>this.supportedTypes.includes(o.type));return console.log("[IMAGE-UPLOAD] hasImageFiles - result:",i),i}filterImageFiles(e){return Array.from(e).filter(i=>this.supportedTypes.includes(i.type))}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var Ot=class n{pendingFirstMessage=null;setPendingFirstMessage(e){console.log("[FIRST-MESSAGE-STATE] Storing pending first message:",e.substring(0,50)+"..."),this.pendingFirstMessage=e}consumePendingFirstMessage(){let e=this.pendingFirstMessage;return e?(console.log("[FIRST-MESSAGE-STATE] Consuming pending first message:",e.substring(0,50)+"..."),this.pendingFirstMessage=null):console.log("[FIRST-MESSAGE-STATE] No pending first message to consume"),e}hasPendingFirstMessage(){return this.pendingFirstMessage!==null}clear(){this.pendingFirstMessage&&(console.log("[FIRST-MESSAGE-STATE] Clearing pending first message"),this.pendingFirstMessage=null)}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var td=["inputSection"],nd=()=>[];function id(n,e){if(n&1){let t=E();c(0,"button",20),w("click",function(){C(t);let o=m();return y(o.toggleFileDrawer())}),c(1,"mat-icon"),f(2,"folder_open"),d()()}if(n&2){let t=m();fe("has-files",t.fileCount>0),k("title",No("Files Exchange",t.fileCount>0?" ("+t.fileCount+" file"+(t.fileCount>1?"s":"")+")":""))("matBadge",t.fileCount>0?t.fileCount:null)}}function od(n,e){if(n&1){let t=E();c(0,"button",21),w("click",function(){C(t);let o=m();return y(o.toggleSharePanel())}),c(1,"mat-icon"),f(2,"group"),d()()}if(n&2){let t=m();fe("has-shared-users",((t.threadDetails==null||t.threadDetails.users==null?null:t.threadDetails.users.length)??0)>1)}}function rd(n,e){if(n&1&&(c(0,"div",6),f(1),d()),n&2){let t=m();p(),ln(" \u26A0\uFE0F Connection lost. Reconnecting... (",t.connectionStatus.reconnectAttempts,"/",t.connectionStatus.maxAttempts,") ")}}function ad(n,e){if(n&1&&(c(0,"div",22),f(1),d()),n&2){let t=m();fe("error",t.uploadStatus.isError),p(),ut(" ",t.uploadStatus.message," ")}}function sd(n,e){if(n&1){let t=E();c(0,"app-chat-textarea",23),w("messageSubmitted",function(o){C(t);let r=m();return y(r.onMessageSubmitted(o))})("voiceRecordingToggled",function(o){C(t);let r=m();return y(r.onVoiceToggled(o))})("heightChanged",function(o){C(t);let r=m();return y(r.onInputHeightChanged(o))})("stopRequested",function(){C(t);let o=m();return y(o.onStopRequested())})("filesPasted",function(o){C(t);let r=m();return y(r.onFilesPasted(o))}),d()}if(n&2){let t=m();k("isDisabled",!t.isConnected)("isSessionInitializing",!1)("showWelcome",!1)("isThinking",t.isThinking)("isStarting",!1)}}function ld(n,e){if(n&1){let t=E();c(0,"app-choice-select",24),w("choiceSelected",function(o){C(t);let r=m();return y(r.onChoiceSelected(o))}),d()}if(n&2){let t=m();k("options",t.currentChoice.options)("labelHtml",t.currentChoice.label)("isVisible",!!t.currentChoice)("allowFreeText",t.currentChoice.allowFreeText)}}function cd(n,e){n&1&&A(0,"app-oauth-request-panel")}function dd(n,e){if(n&1){let t=E();c(0,"app-file-exchange-drawer",25),w("closeDrawer",function(){C(t);let o=m();return y(o.closeDrawer())}),d()}if(n&2){let t=m();k("projectName",t.projectName)("threadId",t.threadId)}}function pd(n,e){if(n&1){let t=E();c(0,"app-thread-share",26),w("userAdded",function(o){C(t);let r=m();return y(r.onUserAdded(o))})("userRemoved",function(o){C(t);let r=m();return y(r.onUserRemoved(o))})("closed",function(){C(t);let o=m();return y(o.closeDrawer())}),d()}if(n&2){let t=m();k("threadId",t.threadId)("users",t.threadDetails.users||Ho(3,nd))("currentUsername",t.currentUsername)}}function md(n,e){n&1&&(c(0,"div",19)(1,"div",27)(2,"div",28),f(3,"\u{1F4CE}"),d(),c(4,"div",29),f(5,"Drop files here to upload"),d(),c(6,"div",30),f(7,"Images will be added to conversation, other files to exchange space"),d()()())}var ni=class n{projectName;threadId;chatFocused=new H;drawerStateChange=new H;destroy$=new oe;connectionDestroy$=new oe;inputSection;messages=[];streamingText="";isThinking=!1;currentChoice=null;connectionStatus=null;isConnected=!1;showConnectionStatus=!1;hasEverConnected=!1;inputSectionHeight=80;uploadStatus={message:"",isError:!1};isDragOver=!1;drawerMode="none";get isDrawerOpen(){return this.drawerMode!=="none"}threadDetails=null;threadShareRef;get fileCount(){return this.fileExchangeState.fileCount()}currentUsername="";authEnabled=!1;pendingFirstMessage=null;subscriptions=[];codayService=h(Ce);oauthService=h(En);pendingOAuthRequest=kn(this.oauthService.pendingRequest$,{initialValue:null});preferencesService=h(ve);titleService=h(Et);elementRef=h(mt);threadState=h(gt);threadApiService=h(ht);userService=h(Ko);router=h(gn);imageUploadService=h(ti);fileExchangeState=h(Ct);firstMessageState=h(Ot);ngOnInit(){if(console.log("[THREAD] Initializing with project:",this.projectName,"thread:",this.threadId),!this.projectName||!this.threadId){console.error("[THREAD] Missing required inputs: projectName or threadId");return}this.setupPrintHandlers(),this.userService.authEnabled$.pipe(B(this.destroy$)).subscribe(e=>{this.authEnabled=e}),this.userService.username$.pipe(B(this.destroy$)).subscribe(e=>{this.currentUsername=e??"",this.messages.length>0&&(this.messages=[...this.messages])}),this.initializeThreadConnection()}ngOnChanges(e){console.log("[THREAD] ngOnChanges called",e),e.threadId&&(console.log("[THREAD] threadId changed:",{firstChange:e.threadId.firstChange,previousValue:e.threadId.previousValue,currentValue:e.threadId.currentValue}),e.threadId.firstChange||(console.log("[THREAD] Reconnecting to new thread"),this.initializeThreadConnection()))}initializeThreadConnection(){console.log("[THREAD] Initializing connection for thread:",this.threadId),this.fileExchangeState.initializeForThread(this.projectName,this.threadId),this.connectionDestroy$.next(),this.codayService.messages$.pipe(B(this.connectionDestroy$)).subscribe(t=>{console.log("[THREAD] Messages updated:",t.length),this.messages=t}),this.codayService.streamingText$.pipe(B(this.connectionDestroy$)).subscribe(t=>{this.streamingText=t}),this.codayService.isThinking$.pipe(B(this.connectionDestroy$)).subscribe(t=>{this.isThinking=t}),this.codayService.currentChoice$.pipe(B(this.connectionDestroy$)).subscribe(t=>{this.currentChoice=t}),this.codayService.connectionStatus$.pipe(B(this.connectionDestroy$)).subscribe(t=>{this.connectionStatus=t,this.isConnected=t.connected,t.connected&&!this.hasEverConnected&&(this.hasEverConnected=!0,this.showConnectionStatus=!0),!t.connected&&!this.hasEverConnected?setTimeout(()=>{!this.isConnected&&!this.hasEverConnected&&(this.showConnectionStatus=!0)},2e3):!t.connected&&this.hasEverConnected?this.showConnectionStatus=!0:t.connected&&(this.showConnectionStatus=!0)}),this.codayService.threadUpdateEvent$.pipe(B(this.connectionDestroy$)).subscribe(t=>{t&&(console.log("[THREAD] Thread update event received:",t),this.threadState.refreshThreadList())}),this.threadState.selectedThread$.pipe(B(this.connectionDestroy$)).subscribe(t=>{this.threadDetails=t}),this.codayService.resetMessages(),this.codayService.setTabTitleService(this.titleService),console.log("[THREAD] Connecting to thread event stream"),this.codayService.connectToThread(this.projectName,this.threadId),this.threadApiService.getThreadMessages(this.threadId).pipe(B(this.connectionDestroy$)).subscribe({next:({messages:t})=>{console.log("[THREAD] Loaded",t.length,"messages from REST history"),this.codayService.loadHistoryFromRest(t)},error:t=>console.warn("[THREAD] Could not load REST history:",t)});let e=this.firstMessageState.consumePendingFirstMessage();e?(console.log("[THREAD] First message pending:",e.substring(0,50)+"..."),this.pendingFirstMessage=e,this.codayService.setThinkingForPendingMessage(),this.subscribeToFirstInvite()):console.log("[THREAD] No first message found in state service")}ngAfterViewChecked(){if(this.inputSection?.nativeElement){let e=this.inputSection.nativeElement.offsetHeight;e!==this.inputSectionHeight&&e>0&&(this.inputSectionHeight=e)}}ngOnDestroy(){console.log("[THREAD] Destroying component"),this.connectionDestroy$.next(),this.connectionDestroy$.complete(),this.destroy$.next(),this.destroy$.complete(),this.fileExchangeState.clear(),this.subscriptions.forEach(e=>e.unsubscribe()),this.subscriptions=[],window.removeEventListener("beforeprint",this.handleBeforePrint),window.removeEventListener("afterprint",this.handleAfterPrint)}onMessageSubmitted(e){console.log("[THREAD] Sending message:",e),this.codayService.sendMessage(e)}onVoiceToggled(e){console.log("[VOICE] Recording:",e)}onChoiceSelected(e){console.log("[THREAD] Choice selected:",e),this.codayService.sendChoice(e)}onCopyMessage(e){console.log("[COPY] Message copied:",e.id)}onStopRequested(){this.threadState.stop()}onInputHeightChanged(e){console.log("[THREAD] Input height changed:",e),this.inputSectionHeight=e}onFilesPasted(e){console.log("[THREAD] File(s) pasted:",e.length);let t=this.imageUploadService.filterImageFiles(e),i=e.filter(o=>!o.type.startsWith("image/"));t.length&&this.uploadFilesSequentially(t,0),i.length&&this.uploadFilesToExchangeSpace(i),!t.length&&!i.length&&this.showUploadError("No supported files found")}emitDrawerState(){this.drawerStateChange.emit(this.isDrawerOpen)}toggleFileDrawer(){this.drawerMode=this.drawerMode==="files"?"none":"files",this.emitDrawerState()}toggleSharePanel(){this.drawerMode=this.drawerMode==="share"?"none":"share",this.emitDrawerState()}closeDrawer(){this.drawerMode="none",this.emitDrawerState()}onUserAdded(e){if(console.log("[THREAD] Adding user to thread:",e),!this.threadDetails)return;let t=this.threadDetails.users||[];if(t.some(o=>o.userId===e)){this.threadShareRef?.setError("User already has access to this thread");return}this.threadShareRef?.setAdding(!0);let i=[...t,{userId:e}];this.threadState.updateThreadUsers(this.threadId,i).pipe(B(this.destroy$)).subscribe({next:()=>{console.log("[THREAD] User added successfully"),this.threadShareRef?.setAdding(!1),this.threadState.refreshSelectedThread()},error:o=>{console.error("[THREAD] Error adding user:",o),this.threadShareRef?.setError(o?.error?.error||"Failed to add user")}})}onUserRemoved(e){if(console.log("[THREAD] Removing user from thread:",e),!this.threadDetails)return;let t=e===this.currentUsername,i=(this.threadDetails.users||[]).filter(o=>o.userId!==e);this.threadState.updateThreadUsers(this.threadId,i).pipe(B(this.destroy$)).subscribe({next:()=>{console.log("[THREAD] User removed successfully"),t?(this.threadState.clearSelection(),this.threadState.refreshThreadList(),this.router.navigate(["project",this.projectName])):this.threadState.refreshSelectedThread()},error:o=>{console.error("[THREAD] Error removing user:",o)}})}onDragEnter(e){e.preventDefault(),e.dataTransfer?.types.includes("Files")&&(console.log("[THREAD] Image files detected - showing drag overlay"),this.isDragOver=!0)}onDragOver(e){e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect="copy")}onDragLeave(e){this.elementRef.nativeElement.contains(e.relatedTarget)||(console.log("[THREAD] Leaving component area - hiding drag overlay"),this.isDragOver=!1)}onDrop(e){e.preventDefault(),this.isDragOver=!1,console.log("[THREAD] Files dropped:",e.dataTransfer?.files?.length||0);let t=e.dataTransfer?.files;if(!t||t.length===0){console.log("[THREAD] No files in drop event");return}let i=this.imageUploadService.filterImageFiles(t),o=Array.from(t).filter(r=>!r.type.startsWith("image/"));console.log("[THREAD] Image files:",i.length,"Other files:",o.length),i.length>0&&this.uploadFilesSequentially(i,0),o.length>0&&this.uploadFilesToExchangeSpace(o),i.length===0&&o.length===0&&this.showUploadError("No supported files found")}uploadFilesSequentially(e,t){if(t>=e.length)return;let i=e[t];if(!i){console.error("[THREAD] File at index",t,"is undefined");return}console.log("[THREAD] Uploading file:",i.name),this.uploadStatus={message:`Uploading ${i.name}...`,isError:!1},this.imageUploadService.uploadImage(i,this.projectName,this.threadId).subscribe({next:o=>{o.success?(console.log("[THREAD] Upload successful:",i.name),this.uploadStatus={message:`\u2713 ${i.name} uploaded (${(o.processedSize/1024).toFixed(1)} KB)`,isError:!1},setTimeout(()=>{this.uploadStatus.isError||(this.uploadStatus={message:"",isError:!1})},3e3),this.uploadFilesSequentially(e,t+1)):(console.error("[THREAD] Upload failed:",i.name,o.error),this.showUploadError(`Failed to upload ${i.name}: ${o.error}`))},error:o=>{console.error("[THREAD] Upload error:",i.name,o),this.showUploadError(`Failed to upload ${i.name}: ${o.message||"Unknown error"}`)}})}showUploadError(e){this.uploadStatus={message:e,isError:!0},setTimeout(()=>{this.uploadStatus={message:"",isError:!1}},5e3)}uploadFilesToExchangeSpace(e){return L(this,null,function*(){for(let t of e){console.log("[THREAD] Uploading to exchange space:",t.name),this.uploadStatus={message:`Uploading ${t.name}...`,isError:!1};let i=yield this.fileExchangeState.uploadFile(t);if(i.success)console.log("[THREAD] Upload to exchange space successful:",t.name),this.uploadStatus={message:`\u2713 ${t.name} uploaded to exchange space`,isError:!1},setTimeout(()=>{this.uploadStatus.isError||(this.uploadStatus={message:"",isError:!1})},3e3);else{console.error("[THREAD] Upload to exchange space failed:",t.name,i.error),this.showUploadError(`Failed to upload ${t.name}: ${i.error}`);break}}})}subscribeToFirstInvite(){console.log("[THREAD] Subscribing to wait for InviteEvent"),this.subscriptions.push(this.codayService.currentInviteEvent$.subscribe(e=>{if(e&&this.pendingFirstMessage){console.log("[THREAD] Received InviteEvent, sending pending message");let t=this.pendingFirstMessage;this.pendingFirstMessage=null,this.codayService.sendMessage(t)}}))}setupPrintHandlers(){window.addEventListener("beforeprint",this.handleBeforePrint),window.addEventListener("afterprint",this.handleAfterPrint)}handleBeforePrint=()=>{console.log("[PRINT] Before print event triggered");let e=this.preferencesService.getPrintTechnicalMessages();console.log("[PRINT] Print technical messages:",e),e?document.body.classList.add("print-include-technical"):document.body.classList.remove("print-include-technical")};handleAfterPrint=()=>{console.log("[PRINT] After print event triggered"),document.body.classList.remove("print-include-technical")};static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-thread"]],viewQuery:function(t,i){if(t&1&&Be(td,5)(Gt,5),t&2){let o;be(o=xe())&&(i.inputSection=o.first),be(o=xe())&&(i.threadShareRef=o.first)}},inputs:{projectName:"projectName",threadId:"threadId"},outputs:{chatFocused:"chatFocused",drawerStateChange:"drawerStateChange"},features:[Ie],decls:22,vars:16,consts:[["inputSection",""],[1,"drag-drop-wrapper",3,"dragenter","dragover","dragleave","drop"],[1,"file-drawer-container",3,"hasBackdrop"],[1,"thread-container"],["matFab","","type","button",1,"file-drawer-toggle-btn",3,"has-files","matBadge","title"],["matFab","","title","Share thread","type","button",1,"share-toggle-btn",3,"has-shared-users"],[1,"connection-status"],[1,"chat-wrapper",3,"mousedown","touchstart"],[1,"chat-center"],[3,"copyRequested","stopRequested","messages","streamingText","isThinking","currentUsername"],[1,"upload-status",3,"error"],[1,"input-section"],[1,"input-center"],[1,"input-glass"],[3,"isDisabled","isSessionInitializing","showWelcome","isThinking","isStarting"],[1,"choice-overlay",3,"options","labelHtml","isVisible","allowFreeText"],["mode","side","position","end",3,"closed","opened"],[3,"projectName","threadId"],[3,"threadId","users","currentUsername"],[1,"drag-overlay"],["matFab","","type","button",1,"file-drawer-toggle-btn",3,"click","matBadge","title"],["matFab","","title","Share thread","type","button",1,"share-toggle-btn",3,"click"],[1,"upload-status"],[3,"messageSubmitted","voiceRecordingToggled","heightChanged","stopRequested","filesPasted","isDisabled","isSessionInitializing","showWelcome","isThinking","isStarting"],[1,"choice-overlay",3,"choiceSelected","options","labelHtml","isVisible","allowFreeText"],[3,"closeDrawer","projectName","threadId"],[3,"userAdded","userRemoved","closed","threadId","users","currentUsername"],[1,"drag-overlay-content"],[1,"drag-icon"],[1,"drag-text"],[1,"drag-hint"]],template:function(t,i){t&1&&(c(0,"div",1),w("dragenter",function(r){return i.onDragEnter(r)})("dragover",function(r){return i.onDragOver(r)})("dragleave",function(r){return i.onDragLeave(r)})("drop",function(r){return i.onDrop(r)}),c(1,"mat-drawer-container",2)(2,"mat-drawer-content")(3,"div",3),x(4,id,3,5,"button",4),x(5,od,3,2,"button",5),x(6,rd,2,2,"div",6),c(7,"div",7),w("mousedown",function(){return i.chatFocused.emit()})("touchstart",function(){return i.chatFocused.emit()}),c(8,"div",8)(9,"app-chat-history",9),w("copyRequested",function(r){return i.onCopyMessage(r)})("stopRequested",function(){return i.onStopRequested()}),d(),x(10,ad,2,3,"div",10),d()(),c(11,"div",11,0)(13,"div",12)(14,"div",13),x(15,sd,1,5,"app-chat-textarea",14),x(16,ld,1,4,"app-choice-select",15),x(17,cd,1,0,"app-oauth-request-panel"),d()()()()(),c(18,"mat-drawer",16),w("closed",function(){return i.closeDrawer()}),x(19,dd,1,2,"app-file-exchange-drawer",17),x(20,pd,1,4,"app-thread-share",18),d()(),x(21,md,8,0,"div",19),d()),t&2&&(p(),k("hasBackdrop",!1),p(3),_(i.drawerMode!=="files"?4:-1),p(),_(i.authEnabled&&i.drawerMode!=="share"?5:-1),p(),_(i.showConnectionStatus&&i.connectionStatus&&!i.connectionStatus.connected?6:-1),p(3),k("messages",i.messages)("streamingText",i.streamingText)("isThinking",i.isThinking)("currentUsername",i.currentUsername),p(),_(i.uploadStatus.message?10:-1),p(5),_(!i.currentChoice&&!i.pendingOAuthRequest()?15:-1),p(),_(i.currentChoice?16:-1),p(),_(i.pendingOAuthRequest()?17:-1),p(),k("opened",i.isDrawerOpen),p(),_(i.drawerMode==="files"?19:-1),p(),_(i.drawerMode==="share"&&i.threadDetails?20:-1),p(),_(i.isDragOver?21:-1))},dependencies:[Vn,ft,Un,Bn,Kn,Gt,ur,pr,mr,dr,he,J,qe,xn,Oa,Ea],styles:[".drag-drop-wrapper[_ngcontent-%COMP%]{height:100vh;height:100dvh;width:100%;position:relative}.thread-container[_ngcontent-%COMP%]{display:flex;flex-direction:column;height:100%;width:100%;position:relative;background:transparent}.file-drawer-toggle-btn[_ngcontent-%COMP%]{position:fixed!important;top:1rem!important;right:1rem!important;z-index:100!important}.file-drawer-toggle-btn.has-files[_ngcontent-%COMP%]{animation:_ngcontent-%COMP%_pulse-subtle 3s infinite}@media(max-width:768px){.file-drawer-toggle-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;top:.75rem!important;right:.75rem!important}.file-drawer-toggle-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}.share-toggle-btn[_ngcontent-%COMP%]{position:fixed!important;top:5rem!important;right:1rem!important;z-index:100!important}.share-toggle-btn.has-shared-users[_ngcontent-%COMP%]{color:var(--color-primary)!important}@media(max-width:768px){.share-toggle-btn[_ngcontent-%COMP%]{width:40px!important;height:40px!important;top:calc(1.25rem + 40px)!important;right:.75rem!important}.share-toggle-btn[_ngcontent-%COMP%] mat-icon[_ngcontent-%COMP%]{font-size:20px;width:20px;height:20px}}@keyframes _ngcontent-%COMP%_pulse-subtle{0%,to{box-shadow:0 2px 8px #00000026}50%{box-shadow:0 4px 16px rgba(var(--color-primary-rgb, 25, 118, 210),.3)}}.file-drawer-container[_ngcontent-%COMP%]{height:100dvh;width:100%;background:var(--color-bg)}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer-content{display:flex;flex-direction:column;height:100%;overflow:hidden;background:transparent}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer{width:35%;min-width:280px;max-width:480px;box-shadow:-2px 0 8px #0000001a}@media(max-width:768px){.file-drawer-container[_ngcontent-%COMP%] .mat-drawer{width:100%;max-width:100%;padding-bottom:env(safe-area-inset-bottom,0px)}}.file-drawer-container[_ngcontent-%COMP%] .mat-drawer-backdrop{display:none}.connection-status[_ngcontent-%COMP%]{position:fixed;top:0;left:0;right:0;z-index:1000;background:var(--color-warning);color:var(--color-text);padding:.5rem 1rem;text-align:center;font-size:.9rem;box-shadow:0 2px 4px #0000001a}.chat-wrapper[_ngcontent-%COMP%]{flex:1;overflow-y:auto;overflow-x:hidden;display:flex;flex-direction:column;width:100%;padding:1rem 0}.chat-center[_ngcontent-%COMP%]{max-width:800px;width:100%;margin:0 auto;padding:0 2rem;display:flex;flex-direction:column;gap:1rem}@media(max-width:768px){.chat-center[_ngcontent-%COMP%]{padding:0 1rem}}.input-section[_ngcontent-%COMP%]{width:100%;padding:1rem 0;padding-bottom:calc(1rem + env(safe-area-inset-bottom,0px));background:transparent;position:relative}.input-center[_ngcontent-%COMP%]{max-width:800px;width:100%;margin:0 auto;padding:0 2rem}@media(max-width:768px){.input-center[_ngcontent-%COMP%]{padding:0 1rem}}.choice-overlay[_ngcontent-%COMP%]{display:block;width:100%}.upload-status[_ngcontent-%COMP%]{padding:.75rem 1rem;border-radius:8px;background:var(--color-success-light);color:var(--color-text);font-size:.9rem;text-align:center}.upload-status.error[_ngcontent-%COMP%]{background:var(--color-error-light)}@media print{.file-drawer-toggle-btn[_ngcontent-%COMP%], .share-toggle-btn[_ngcontent-%COMP%], .connection-status[_ngcontent-%COMP%]{display:none}.thread-container[_ngcontent-%COMP%]{background:#fff}.input-section[_ngcontent-%COMP%]{display:none}}"]})};var ii=class n{welcomeMessages=["Welcome to Coday","Bienvenue sur Coday","Bienvenido a Coday","Willkommen bei Coday","Benvenuto su Coday","Bem-vindo ao Coday","Welkom bij Coday","\u0414\u043E\u0431\u0440\u043E \u043F\u043E\u0436\u0430\u043B\u043E\u0432\u0430\u0442\u044C \u0432 Coday","Coday \u3078\u3088\u3046\u3053\u305D","\u6B22\u8FCE\u6765\u5230 Coday","Coday \uC5D0 \uC624\uC2E0 \uAC83\uC744 \uD658\uC601\uD569\uB2C8\uB2E4","\u0645\u0631\u062D\u0628\u064B\u0627 \u0628\u0643 \u0641\u064A Coday"];currentWelcomeIndex=0;currentWelcomeMessage=this.welcomeMessages[0];welcomeRotationInterval;ngOnInit(){this.startWelcomeRotation()}ngOnDestroy(){this.stopWelcomeRotation()}startWelcomeRotation(){this.welcomeRotationInterval=window.setInterval(()=>{this.currentWelcomeIndex=(this.currentWelcomeIndex+1)%this.welcomeMessages.length,this.currentWelcomeMessage=this.welcomeMessages[this.currentWelcomeIndex]},3e3)}stopWelcomeRotation(){this.welcomeRotationInterval&&(clearInterval(this.welcomeRotationInterval),this.welcomeRotationInterval=void 0)}static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-welcome-message"]],decls:2,vars:1,consts:[[1,"welcome-title"]],template:function(t,i){t&1&&(Rt(0,"h1",0),f(1),Ft()),t&2&&(p(),D(i.currentWelcomeMessage))},styles:[".welcome-title[_ngcontent-%COMP%]{font-size:clamp(1.5rem,4vw,4rem);font-weight:700;background:linear-gradient(90deg,var(--color-primary, #3b82f6) 0%,var(--color-accent, #8b5cf6) 50%,var(--color-primary, #3b82f6) 100%);background-size:200% auto;background-clip:text;-webkit-background-clip:text;-webkit-text-fill-color:transparent;animation:_ngcontent-%COMP%_gradientShift 3s ease-in-out infinite;margin:0;padding:0;line-height:1.2;transition:opacity .5s ease-in-out;display:block;min-height:1.2em;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@keyframes _ngcontent-%COMP%_gradientShift{0%{background-position:0% center}50%{background-position:100% center}to{background-position:0% center}}"]})};var oi=class n{destroy$=new oe;isSetup=!1;codayService=h(Ce);preferencesService=h(ve);setup(){if(this.isSetup){console.warn("[AGENT-NOTIFICATION] Service already set up");return}console.log("[AGENT-NOTIFICATION] Setting up agent notification service"),this.codayService.isThinking$.pipe(B(this.destroy$),Ci(),we(([e,t])=>e===!0&&t===!1)).subscribe(()=>{console.log("[AGENT-NOTIFICATION] Agent stopped thinking, notifying task finished"),this.notifyTaskFinishedIfEnabled()}),this.preferencesService.browserNotificationEnabled$.pipe(B(this.destroy$),Ci(),we(([e,t])=>e===!1&&t===!0)).subscribe(()=>{console.log("[AGENT-NOTIFICATION] Browser notifications enabled, checking permission"),this.handleBrowserNotificationEnabled()}),this.isSetup=!0}notifyTaskFinishedIfEnabled(){this.preferencesService.getAgentNotificationEnabled()&&(this.preferencesService.getNotificationSoundEnabled()&&this.playCompletionSound(),this.preferencesService.getBrowserNotificationEnabled()&&this.sendBrowserNotification())}playCompletionSound(){try{let e=new(window.AudioContext||window.webkitAudioContext),t=e.createOscillator(),i=e.createGain();t.connect(i),i.connect(e.destination),t.frequency.setValueAtTime(700,e.currentTime),i.gain.setValueAtTime(.1,e.currentTime),i.gain.exponentialRampToValueAtTime(.01,e.currentTime+.08),t.start(e.currentTime),t.stop(e.currentTime+.08);let o=e.createOscillator(),r=e.createGain();o.connect(r),r.connect(e.destination);let a=e.currentTime+.11;o.frequency.setValueAtTime(950,a),r.gain.setValueAtTime(.1,a),r.gain.exponentialRampToValueAtTime(.01,a+.09),o.start(a),o.stop(a+.09),console.log("[AGENT-NOTIFICATION] Completion sound played")}catch(e){console.error("[AGENT-NOTIFICATION] Failed to play completion sound:",e)}}handleBrowserNotificationEnabled(){return L(this,null,function*(){if(!("Notification"in window)){console.warn("[AGENT-NOTIFICATION] Browser does not support notifications"),this.preferencesService.setBrowserNotificationEnabled(!1);return}if(Notification.permission==="denied"){console.warn("[AGENT-NOTIFICATION] Permission denied, disabling browser notifications"),this.preferencesService.setBrowserNotificationEnabled(!1);return}if(Notification.permission==="granted"){console.log("[AGENT-NOTIFICATION] Permission already granted, showing confirmation"),this.createConfirmationNotification();return}try{(yield Notification.requestPermission())==="granted"?(console.log("[AGENT-NOTIFICATION] Permission granted, showing confirmation"),this.createConfirmationNotification()):(console.log("[AGENT-NOTIFICATION] Permission denied or dismissed"),this.preferencesService.setBrowserNotificationEnabled(!1))}catch(e){console.error("[AGENT-NOTIFICATION] Error requesting permission:",e),this.preferencesService.setBrowserNotificationEnabled(!1)}})}sendBrowserNotification(){if(!("Notification"in window)){console.warn("[AGENT-NOTIFICATION] Browser does not support notifications");return}if(document.hasFocus()){console.warn("[AGENT-NOTIFICATION] Document is focused, skipping browser notification");return}Notification.permission==="granted"?this.createTaskCompleteNotification():console.warn("[AGENT-NOTIFICATION] Permission not granted, cannot send notification")}createConfirmationNotification(){let e=new Notification("Coday - Notifications Enabled",{body:"You will be notified when the agent completes tasks",icon:"/favicon.ico",tag:"coday-notifications-enabled",requireInteraction:!1});setTimeout(()=>e.close(),4e3),e.onclick=()=>{window.focus(),e.close()},console.log("[AGENT-NOTIFICATION] Confirmation notification sent")}createTaskCompleteNotification(){let e=new Notification("Coday - Task Complete",{body:"The agent has finished and is waiting for your input",icon:"/favicon.ico",tag:"coday-task-complete",requireInteraction:!1});setTimeout(()=>e.close(),5e3),e.onclick=()=>{window.focus(),e.close()},console.log("[AGENT-NOTIFICATION] Task complete notification sent")}ngOnDestroy(){console.log("[AGENT-NOTIFICATION] Service destroyed"),this.destroy$.next(),this.destroy$.complete()}static \u0275fac=function(t){return new(t||n)};static \u0275prov=Y({token:n,factory:n.\u0275fac,providedIn:"root"})};var ud=["inputSection"];function hd(n,e){if(n&1){let t=E();c(0,"app-thread",4),w("chatFocused",function(){C(t);let o=m();return y(o.onChatFocusedOnMobile())})("drawerStateChange",function(o){C(t);let r=m();return y(r.onDrawerStateChange(o))}),d()}if(n&2){let t=m();k("projectName",t.projectName)("threadId",t.threadId)}}function gd(n,e){if(n&1){let t=E();c(0,"div",5),A(1,"app-welcome-message"),d(),c(2,"div",6,0)(4,"div",7)(5,"div",8)(6,"app-chat-textarea",9),w("messageSubmitted",function(o){C(t);let r=m();return y(r.onMessageSubmitted(o))})("voiceRecordingToggled",function(o){C(t);let r=m();return y(r.onVoiceToggled(o))})("heightChanged",function(o){C(t);let r=m();return y(r.onInputHeightChanged(o))})("textareaFocused",function(){C(t);let o=m();return y(o.onChatFocusedOnMobile())}),d()()()()}if(n&2){let t=m();p(6),k("isDisabled",t.isSessionInitializing)("isSessionInitializing",t.isSessionInitializing)("showWelcome",!0)("isThinking",!1)("isStarting",t.isStartingFirstMessage)}}var Ia=class n{destroy$=new oe;inputSection;sidenav;projectName="";threadId=null;isSessionInitializing=!1;isStartingFirstMessage=!1;inputSectionHeight=80;codayService=h(Ce);titleService=h(Et);preferencesService=h(ve);route=h(Uo);router=h(gn);threadApiService=h(ht);agentNotificationService=h(oi);firstMessageState=h(Ot);constructor(){console.log("[MAIN-APP] Using new thread-based architecture (no clientId needed)")}ngOnInit(){this.agentNotificationService.setup(),this.setupPrintHandlers(),this.route.params.pipe(B(this.destroy$)).subscribe(e=>{let t=e.projectName,i=e.threadId||null;console.log("[MAIN-APP] Route params updated:",{project:t,thread:i,previousProject:this.projectName,previousThread:this.threadId}),this.projectName=t,this.threadId=i,this.threadId?console.log("[MAIN-APP] Thread selected - ThreadComponent will display"):(console.log("[MAIN-APP] No thread selected - showing welcome view"),this.initializeWelcomeView())})}initializeWelcomeView(){this.codayService.setTabTitleService(this.titleService)}ngAfterViewInit(){setTimeout(()=>this.updateInputSectionHeight(),100)}ngOnDestroy(){this.destroy$.next(),this.destroy$.complete(),window.removeEventListener("beforeprint",this.handleBeforePrint),window.removeEventListener("afterprint",this.handleAfterPrint)}onMessageSubmitted(e){console.log("[MAIN-APP] First message submitted from welcome view:",e),this.isSessionInitializing=!0,this.isStartingFirstMessage=!0,this.threadApiService.createThread().subscribe({next:t=>{console.log("[MAIN-APP] Thread created:",t.thread.id),this.firstMessageState.setPendingFirstMessage(e),this.router.navigate(["project",this.projectName,"thread",t.thread.id])},error:t=>{console.error("[MAIN-APP] Failed to create thread:",t),this.isSessionInitializing=!1,this.isStartingFirstMessage=!1,alert("Failed to create conversation: "+(t.message||"Unknown error"))}})}onVoiceToggled(e){console.log("[VOICE] Recording in welcome view:",e)}isDrawerOpen=!1;onDrawerStateChange(e){this.isDrawerOpen=e}onChatFocusedOnMobile(){window.innerWidth<1024&&this.sidenav?.close()}onInputHeightChanged(e){console.log("[MAIN-APP] Input height changed:",e),this.inputSectionHeight=e}updateInputSectionHeight(){if(this.inputSection?.nativeElement){let e=this.inputSection.nativeElement.offsetHeight;e!==this.inputSectionHeight&&(console.log("[MAIN-APP] Input section height updated:",e),this.inputSectionHeight=e)}}setupPrintHandlers(){window.addEventListener("beforeprint",this.handleBeforePrint),window.addEventListener("afterprint",this.handleAfterPrint)}handleBeforePrint=()=>{console.log("[PRINT] Before print event triggered");let e=this.preferencesService.getPrintTechnicalMessages();console.log("[PRINT] Print technical messages:",e),e?document.body.classList.add("print-include-technical"):document.body.classList.remove("print-include-technical")};handleAfterPrint=()=>{console.log("[PRINT] After print event triggered"),document.body.classList.remove("print-include-technical")};static \u0275fac=function(t){return new(t||n)};static \u0275cmp=P({type:n,selectors:[["app-main"]],viewQuery:function(t,i){if(t&1&&Be(ud,5)(Si,5),t&2){let o;be(o=xe())&&(i.inputSection=o.first),be(o=xe())&&(i.sidenav=o.first)}},decls:4,vars:2,consts:[["inputSection",""],[3,"drawerOpen"],[1,"app",3,"mousedown","touchstart"],[3,"projectName","threadId"],[3,"chatFocused","drawerStateChange","projectName","threadId"],[1,"welcome-section"],[1,"input-section"],[1,"input-center"],[1,"input-glass"],[3,"messageSubmitted","voiceRecordingToggled","heightChanged","textareaFocused","isDisabled","isSessionInitializing","showWelcome","isThinking","isStarting"]],template:function(t,i){t&1&&(c(0,"app-sidenav",1)(1,"div",2),w("mousedown",function(){return i.onChatFocusedOnMobile()})("touchstart",function(){return i.onChatFocusedOnMobile()}),x(2,hd,1,2,"app-thread",3)(3,gd,7,5),d()()),t&2&&(k("drawerOpen",i.isDrawerOpen),p(2),_(i.threadId?2:3))},dependencies:[ft,ni,ii,Si],styles:["[_nghost-%COMP%]{display:flex;height:100vh;width:100%;overflow:hidden;justify-content:center}.app[_ngcontent-%COMP%]{width:100%;max-width:100%;min-width:0;height:100%;display:flex;flex-direction:column;background:var(--color-bg);color:var(--color-text);transition:all .3s ease;position:relative;justify-content:center;overflow:hidden}.chat-wrapper[_ngcontent-%COMP%]{flex:1;min-height:0;overflow-y:auto;overflow-x:hidden;background:transparent;width:100%;padding:2.5rem 0 1.5rem;display:flex;justify-content:center}.chat-wrapper[_ngcontent-%COMP%] .chat-center[_ngcontent-%COMP%]{max-width:760px;width:100%;margin:0;padding:0 2rem}@media(max-width:768px){.chat-wrapper[_ngcontent-%COMP%] .chat-center[_ngcontent-%COMP%]{padding:0 1rem}}.welcome-section[_ngcontent-%COMP%]{flex-shrink:0;text-align:center;padding:2rem 1rem;animation:_ngcontent-%COMP%_fadeInUp .8s ease-out;display:flex;justify-content:center;align-items:center;width:100%;min-width:0;overflow:hidden}@keyframes _ngcontent-%COMP%_fadeInUp{0%{opacity:0;transform:translateY(20px)}to{opacity:1;transform:translateY(0)}}.input-section[_ngcontent-%COMP%]{flex-shrink:0;position:relative;border-top:none;background:transparent;box-shadow:none;padding:2.5rem 0 2rem;overflow-y:visible;max-height:none;width:100%;z-index:10;pointer-events:none;display:flex;justify-content:center}.input-center[_ngcontent-%COMP%]{max-width:760px;width:100%;margin:0;padding:0 2rem;display:flex;justify-content:center;align-items:end;position:relative;pointer-events:auto}@media(max-width:768px){.input-center[_ngcontent-%COMP%]{padding:0 1rem}}.input-glass[_ngcontent-%COMP%]{background:none;box-shadow:none;width:100%;min-height:64px;display:flex;align-items:stretch;gap:0;pointer-events:auto;position:relative;overflow:visible}.input-glass[_ngcontent-%COMP%] app-chat-textarea[_ngcontent-%COMP%]{width:100%;min-width:0;flex:1 1 auto;align-self:stretch;display:flex}body.dark[_nghost-%COMP%], body.dark [_nghost-%COMP%], [_ngcontent-%COMP%]:root[data-theme=dark] .input-glass[_ngcontent-%COMP%]{background:#24283073;border-color:#b4c8ff17;box-shadow:0 8px 32px #0000002b,0 1.5px 8px #00000012}.choice-overlay[_ngcontent-%COMP%]{z-index:10;width:100%;display:flex;justify-content:center;align-items:center}.upload-status[_ngcontent-%COMP%]{position:fixed;bottom:100px;left:50%;transform:translate(-50%);z-index:1000;display:flex;align-items:center;padding:12px 20px;background:var(--glass-bg);backdrop-filter:var(--glass-backdrop-blur);-webkit-backdrop-filter:var(--glass-backdrop-blur);border:1px solid var(--glass-border);border-radius:16px;font-size:.9em;color:var(--color-text);box-shadow:var(--glass-shadow);max-width:300px;text-align:center}.upload-status.error[_ngcontent-%COMP%]{background:#ff3b3026;color:var(--color-error);border-color:#ff3b304d}@media(max-width:768px){.welcome-section[_ngcontent-%COMP%]{padding:1.5rem 1rem}.input-section[_ngcontent-%COMP%]{padding:1.5rem .75rem 1rem}.input-center[_ngcontent-%COMP%]{padding:0 .5rem}}@media print{[_nghost-%COMP%]{display:block!important;height:auto!important;overflow:visible!important}.app[_ngcontent-%COMP%]{height:auto!important;overflow:visible!important;display:block!important}.input-section[_ngcontent-%COMP%], .welcome-section[_ngcontent-%COMP%]{display:none!important}}"],data:{animation:[Ti("slideIn",[bn(":enter",[Lt({transform:"translateY(100%)",opacity:0}),fn("300ms ease-out",Lt({transform:"translateY(0)",opacity:1}))]),bn(":leave",[fn("200ms ease-in",Lt({transform:"translateY(100%)",opacity:0}))])])]}})};export{Ia as MainAppComponent};
|