@nuraly/lumenui 0.8.0 → 0.8.2
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/dist/nuralyui.bundle.js +121 -58
- package/dist/nuralyui.bundle.js.gz +0 -0
- package/dist/src/components/canvas/bundle.js +135 -61
- package/dist/src/components/canvas/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/bundle.js +103 -29
- package/dist/src/components/chatbot/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/chatbot.component.d.ts +13 -0
- package/dist/src/components/chatbot/chatbot.component.js +50 -5
- package/dist/src/components/chatbot/chatbot.style.js +53 -0
- package/dist/src/components/chatbot/chatbot.types.d.ts +2 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.d.ts +2 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.js +1 -1
- package/dist/src/components/chatbot/templates/message.template.d.ts +3 -1
- package/dist/src/components/chatbot/templates/message.template.js +45 -12
- package/package.json +1 -1
|
Binary file
|
|
@@ -20,12 +20,12 @@ class v{constructor(t){this.t=t=>{"ready"===t.detail.status&&this.host.requestUp
|
|
|
20
20
|
* Copyright 2020 Google LLC
|
|
21
21
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
22
22
|
*/
|
|
23
|
-
class
|
|
23
|
+
class x{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}}
|
|
24
24
|
/**
|
|
25
25
|
* @license
|
|
26
26
|
* Copyright 2014 Travis Webb
|
|
27
27
|
* SPDX-License-Identifier: MIT
|
|
28
|
-
*/const
|
|
28
|
+
*/const y=[];for(let t=0;t<256;t++)y[t]=(t>>4&15).toString(16)+(15&t).toString(16);function w(t,e){return(e?"h":"s")+function(t){let e=0,i=8997,n=0,o=33826,s=0,r=40164,a=0,l=52210;for(let d=0;d<t.length;d++)i^=t.charCodeAt(d),e=435*i,n=435*o,s=435*r,a=435*l,s+=i<<8,a+=o<<8,n+=e>>>16,i=65535&e,s+=n>>>16,o=65535&n,l=a+(s>>>16)&65535,r=65535&s;return y[l>>8]+y[255&l]+y[r>>8]+y[255&r]+y[o>>8]+y[255&o]+y[i>>8]+y[255&i]}
|
|
29
29
|
/**
|
|
30
30
|
* @license
|
|
31
31
|
* Copyright 2020 Google LLC
|
|
@@ -40,7 +40,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
40
40
|
* @license
|
|
41
41
|
* Copyright 2021 Google LLC
|
|
42
42
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
43
|
-
*/(e),o=t[n];if(o){if("string"==typeof o)return o;if("strTag"in o)return p(o.strings,e.values,o.values);{let t=_.get(o);return void 0===t&&(t=o.values,_.set(o,t)),{...o,values:t.map(t=>e.values[t])}}}}return f(e)}function S(t){window.dispatchEvent(new CustomEvent(u,{detail:t}))}let P,M,T,E,C,z="",O=new
|
|
43
|
+
*/(e),o=t[n];if(o){if("string"==typeof o)return o;if("strTag"in o)return p(o.strings,e.values,o.values);{let t=_.get(o);return void 0===t&&(t=o.values,_.set(o,t)),{...o,values:t.map(t=>e.values[t])}}}}return f(e)}function S(t){window.dispatchEvent(new CustomEvent(u,{detail:t}))}let P,M,T,E,C,z="",O=new x;O.resolve();let I=0;const j=t=>(function(t){if(g)throw new Error("lit-localize can only be configured once");m=t,g=!0}((t,e)=>k(C,t,e)),z=M=t.sourceLocale,T=new Set(t.targetLocales),T.add(t.sourceLocale),E=t.loadLocale,{getLocale:R,setLocale:A}),R=()=>z,A=t=>{if(t===(P??z))return O.promise;if(!T||!E)throw new Error("Internal error");if(!T.has(t))throw new Error("Invalid locale code");I++;const e=I;P=t,O.settled&&(O=new x),S({status:"loading",loadingLocale:t});return(t===M?Promise.resolve({templates:void 0}):E(t)).then(i=>{I===e&&(z=t,P=void 0,C=i.templates,S({status:"ready",readyLocale:t}),O.resolve())},i=>{I===e&&(S({status:"error",errorLocale:t,errorMessage:i.toString()}),O.reject(i))}),O.promise};var L=t`
|
|
44
44
|
:host {
|
|
45
45
|
display: block;
|
|
46
46
|
width: 100%;
|
|
@@ -461,6 +461,11 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
461
461
|
justify-content: flex-start; /* Always align messages to top */
|
|
462
462
|
}
|
|
463
463
|
|
|
464
|
+
.messages--inverted {
|
|
465
|
+
flex-direction: column-reverse;
|
|
466
|
+
justify-content: flex-start;
|
|
467
|
+
}
|
|
468
|
+
|
|
464
469
|
.empty-state {
|
|
465
470
|
display: flex;
|
|
466
471
|
flex-direction: column;
|
|
@@ -601,6 +606,54 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
601
606
|
box-shadow: none;
|
|
602
607
|
}
|
|
603
608
|
|
|
609
|
+
.message__text-collapsible {
|
|
610
|
+
position: relative;
|
|
611
|
+
max-height: var(--chatbot-message-collapsed-height, 200px);
|
|
612
|
+
overflow: hidden;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
.message__text-collapsible--expanded {
|
|
616
|
+
max-height: none;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
.message__text-collapsible:not(.message__text-collapsible--expanded)::after {
|
|
620
|
+
content: '';
|
|
621
|
+
position: absolute;
|
|
622
|
+
inset: auto 0 0 0;
|
|
623
|
+
height: 48px;
|
|
624
|
+
pointer-events: none;
|
|
625
|
+
background: linear-gradient(
|
|
626
|
+
to bottom,
|
|
627
|
+
transparent,
|
|
628
|
+
var(--nuraly-color-user-bubble-bg, rgb(124, 58, 237))
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
.message__show-more-toggle {
|
|
633
|
+
margin-top: 6px;
|
|
634
|
+
background: transparent;
|
|
635
|
+
border: 0;
|
|
636
|
+
padding: 4px 0;
|
|
637
|
+
font: inherit;
|
|
638
|
+
font-size: 12px;
|
|
639
|
+
font-weight: 500;
|
|
640
|
+
color: inherit;
|
|
641
|
+
opacity: 0.85;
|
|
642
|
+
cursor: pointer;
|
|
643
|
+
text-decoration: underline;
|
|
644
|
+
text-underline-offset: 2px;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
.message__show-more-toggle:hover {
|
|
648
|
+
opacity: 1;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
.message__show-more-toggle:focus-visible {
|
|
652
|
+
outline: 1px solid currentColor;
|
|
653
|
+
outline-offset: 2px;
|
|
654
|
+
border-radius: 2px;
|
|
655
|
+
}
|
|
656
|
+
|
|
604
657
|
.message.bot .message__content {
|
|
605
658
|
background-color: var(--nuraly-color-bot-bubble-bg, transparent);
|
|
606
659
|
color: var(--nuraly-color-bot-bubble-fg, inherit);
|
|
@@ -1974,20 +2027,34 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1974
2027
|
* @license
|
|
1975
2028
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1976
2029
|
* SPDX-License-Identifier: MIT
|
|
1977
|
-
*/function ht(t){return t.startsWith("image/")}function ut(t,e){const i=t.lastIndexOf(".");if(i>=0&&i<t.length-1)return t.slice(i+1).toUpperCase().slice(0,4);if(e){const t=e.indexOf("/");if(t>=0)return e.slice(t+1).toUpperCase().slice(0,4)}return"FILE"}function pt(t,n,o){var s,r,d,c,h,u
|
|
1978
|
-
<div
|
|
1979
|
-
class="message ${a(g)}"
|
|
1980
|
-
part=${`message message-${v}`}
|
|
1981
|
-
data-sender="${t.sender}"
|
|
1982
|
-
data-id="${t.id}"
|
|
1983
|
-
>
|
|
1984
|
-
<div class="message__content" part=${`message-content message-content-${v}`}>
|
|
1985
|
-
${m?function(t){const e=t.match(/\[ERROR_START\]\[ERROR_TITLE_START\]([\s\S]*?)\[ERROR_TITLE_END\]([\s\S]*?)\[ERROR_END\]/);if(e){const t=e[1],n=e[2];return i`
|
|
2030
|
+
*/function ht(t){return t.startsWith("image/")}function ut(t,e){const i=t.lastIndexOf(".");if(i>=0&&i<t.length-1)return t.slice(i+1).toUpperCase().slice(0,4);if(e){const t=e.indexOf("/");if(t>=0)return e.slice(t+1).toUpperCase().slice(0,4)}return"FILE"}function pt(t,n,o){var s,r,d,c,h,u;const p=null===(s=t.text)||void 0===s?void 0:s.includes("[ERROR_START]"),f={error:!!t.error||p,introduction:!!t.introduction,[t.sender]:!0},m=t.sender,g=null!==(d=null===(r=t.text)||void 0===r?void 0:r.trim())&&void 0!==d?d:"",v=null!==(c=n.collapseThreshold)&&void 0!==c?c:0,b="user"===m&&!p&&v>0&&g.length>v,x=!b||!!(null===(h=n.isExpanded)||void 0===h?void 0:h.call(n,t.id)),y=p?function(t){const e=t.match(/\[ERROR_START\]\[ERROR_TITLE_START\]([\s\S]*?)\[ERROR_TITLE_END\]([\s\S]*?)\[ERROR_END\]/);if(e){const t=e[1],n=e[2];return i`
|
|
1986
2031
|
<div class="message__error-container" part="message-error">
|
|
1987
2032
|
${t?i`<div class="message__error-title" part="message-error-title">${t}</div>`:""}
|
|
1988
2033
|
<div class="message__error-description" part="message-error-description">${n}</div>
|
|
1989
2034
|
</div>
|
|
1990
|
-
`}return i`${t}`}(
|
|
2035
|
+
`}return i`${t}`}(g):(null===(u=null==t?void 0:t.metadata)||void 0===u?void 0:u.renderAsHtml)?l(g):l(g.replaceAll("\n","<br>"));return i`
|
|
2036
|
+
<div
|
|
2037
|
+
class="message ${a(f)}"
|
|
2038
|
+
part=${`message message-${m}`}
|
|
2039
|
+
data-sender="${t.sender}"
|
|
2040
|
+
data-id="${t.id}"
|
|
2041
|
+
>
|
|
2042
|
+
<div class="message__content" part=${`message-content message-content-${m}`}>
|
|
2043
|
+
${b?i`
|
|
2044
|
+
<div
|
|
2045
|
+
class="message__text-collapsible ${x?"message__text-collapsible--expanded":""}"
|
|
2046
|
+
part="message-text-collapsible"
|
|
2047
|
+
>
|
|
2048
|
+
<div class="message__text-inner">${y}</div>
|
|
2049
|
+
</div>
|
|
2050
|
+
<button
|
|
2051
|
+
class="message__show-more-toggle"
|
|
2052
|
+
part="message-show-more"
|
|
2053
|
+
type="button"
|
|
2054
|
+
data-message-toggle="${t.id}"
|
|
2055
|
+
aria-expanded="${x?"true":"false"}"
|
|
2056
|
+
>${x?o.messages.showLessLabel:o.messages.showMoreLabel}</button>
|
|
2057
|
+
`:y}
|
|
1991
2058
|
</div>
|
|
1992
2059
|
${t.files&&t.files.length>0?i`
|
|
1993
2060
|
<div class="message__attachments" part="message-attachments" role="list" aria-label="${o.messages.attachedFilesLabel}">
|
|
@@ -2073,9 +2140,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2073
2140
|
${o.messages.retryButton}
|
|
2074
2141
|
</nr-button>`:e}
|
|
2075
2142
|
</div>
|
|
2076
|
-
`}function ft(t,n,o,s,r,a,l){return i`
|
|
2077
|
-
<div class="messages" part="messages">
|
|
2078
|
-
${0===t.length?l?function(t){return i`
|
|
2143
|
+
`}function ft(t,n,o,s,r,a,l,c){const h=0===t.length?l?function(t){return i`
|
|
2079
2144
|
<div class="empty-state empty-state--loading" part="empty-state thread-loading">
|
|
2080
2145
|
<slot name="thread-loading">
|
|
2081
2146
|
<div class="spinner" part="thread-loading-spinner"></div>
|
|
@@ -2092,8 +2157,17 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2092
2157
|
</div>
|
|
2093
2158
|
</slot>
|
|
2094
2159
|
</div>
|
|
2095
|
-
`}(r,a):e
|
|
2096
|
-
|
|
2160
|
+
`}(r,a):e,u=t=>pt(t,s,r);if(c){const e=[...t].reverse();return i`
|
|
2161
|
+
<div class="messages messages--inverted" part="messages">
|
|
2162
|
+
${o}
|
|
2163
|
+
${n}
|
|
2164
|
+
${d(e,t=>t.id,u)}
|
|
2165
|
+
${h}
|
|
2166
|
+
</div>
|
|
2167
|
+
`}return i`
|
|
2168
|
+
<div class="messages" part="messages">
|
|
2169
|
+
${h}
|
|
2170
|
+
${d(t,t=>t.id,u)}
|
|
2097
2171
|
${n}
|
|
2098
2172
|
${o}
|
|
2099
2173
|
</div>
|
|
@@ -2387,7 +2461,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2387
2461
|
* @license
|
|
2388
2462
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2389
2463
|
* SPDX-License-Identifier: MIT
|
|
2390
|
-
*/function
|
|
2464
|
+
*/function xt(t,e,n){const o=t.messages.length>0?t.messages[t.messages.length-1]:null,s=o&&"string"==typeof o.text?o.text:"";return i`
|
|
2391
2465
|
<div
|
|
2392
2466
|
class="thread-item ${a({"thread-item--active":t.id===e.activeThreadId})}"
|
|
2393
2467
|
@click=${()=>n.onSelectThread(t.id)}
|
|
@@ -2446,7 +2520,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2446
2520
|
</div>
|
|
2447
2521
|
<div class="thread-item__timestamp" part="thread-timestamp">${rt(t.updatedAt)}</div>
|
|
2448
2522
|
</div>
|
|
2449
|
-
`}function
|
|
2523
|
+
`}function yt(t,n){if(!t.isOpen||!t.file)return e;const o=t.file,s=o.mimeType.startsWith("image/"),r="application/pdf"===o.mimeType||o.name.toLowerCase().endsWith(".pdf");return i`
|
|
2450
2524
|
<nr-modal
|
|
2451
2525
|
.open=${t.isOpen}
|
|
2452
2526
|
size="large"
|
|
@@ -2556,7 +2630,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2556
2630
|
${o?i`<span class="loading-text" part="typing-text">${o.split("").map((t,e)=>i`<span class="loading-text__char" style="animation-delay:${.04*e}s">${" "===t?" ":t}</span>`)}</span>`:e}
|
|
2557
2631
|
</div>
|
|
2558
2632
|
</div>
|
|
2559
|
-
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,n.message,t.i18n,t.welcomeMessage,t.isPendingThread)}
|
|
2633
|
+
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,n.message,t.i18n,t.welcomeMessage,t.isPendingThread,t.invertedScroll)}
|
|
2560
2634
|
<slot name="messages"></slot>
|
|
2561
2635
|
</div>
|
|
2562
2636
|
`:t.suggestions&&t.suggestions.length>0?i`
|
|
@@ -2584,14 +2658,14 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2584
2658
|
<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/></svg>
|
|
2585
2659
|
${t.i18n.threads.bookmarksLabel}
|
|
2586
2660
|
</div>
|
|
2587
|
-
${d(o,t=>t.id,e=>
|
|
2661
|
+
${d(o,t=>t.id,e=>xt(e,t,n))}
|
|
2588
2662
|
</div>
|
|
2589
2663
|
`:e}
|
|
2590
2664
|
${s.length>0||0===o.length?i`
|
|
2591
2665
|
${o.length>0?i`
|
|
2592
2666
|
<div class="thread-section__label" part="thread-section-label">${t.i18n.threads.allConversationsLabel}</div>
|
|
2593
2667
|
`:e}
|
|
2594
|
-
${d(s,t=>t.id,e=>
|
|
2668
|
+
${d(s,t=>t.id,e=>xt(e,t,n))}
|
|
2595
2669
|
${0===s.length&&0===o.length?i`
|
|
2596
2670
|
<p class="empty-msg" part="thread-empty">${t.i18n.threads.noConversationsLabel}</p>
|
|
2597
2671
|
`:e}
|
|
@@ -2763,7 +2837,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2763
2837
|
* @license
|
|
2764
2838
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2765
2839
|
* SPDX-License-Identifier: MIT
|
|
2766
|
-
*/var Mt=function(t,e,i,n){for(var o,s=arguments.length,r=s<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,i):n,a=t.length-1;a>=0;a--)(o=t[a])&&(r=(s<3?o(r):s>3?o(e,i,r):o(e,i))||r);return s>3&&r&&Object.defineProperty(e,i,r),r},Tt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})};const Et={input:{placeholder:m("Type your message..."),chatInputAriaLabel:m("Chat input"),attachButton:m("Attach"),attachFilesAriaLabel:m("Attach files"),removeFileLabel:m("Remove file"),uploadingLabel:m("Uploading"),uploadingProgress:m("Uploading…"),dropFilesHere:m("Drop files here to upload")},send:{sendButton:m("Send"),stopButton:m("Stop"),sendMessageLabel:m("Send message"),stopQueryLabel:m("Stop query")},audio:{recordSpeechLabel:m("Record speech to text"),sendVoiceMessageLabel:m("Send voice message"),cancelRecordingLabel:m("Cancel recording"),speechToTextLabel:m("Speech to text"),voiceMessageLabel:m("Voice message"),convertToTextLabel:m("Convert to text"),sendAsVoiceMessageLabel:m("Send as voice message")},modules:{moduleSelectionLabel:m("Select Modules"),moduleSearchPlaceholder:m("Search modules..."),moduleSelectAriaLabel:m("Select modules"),modulesSelectedSuffix:m("modules selected")},threads:{conversationsTitle:m("Conversations"),bookmarksLabel:m("Bookmarks"),allConversationsLabel:m("All Conversations"),noConversationsLabel:m("No conversations yet"),newChatTitle:m("New Chat"),newConversationLabel:m("New conversation"),removeBookmarkLabel:m("Remove bookmark"),bookmarkLabel:m("Bookmark"),renameLabel:m("Rename"),deleteLabel:m("Delete"),moreOptionsLabel:m("More options"),showThreadsLabel:m("Show threads"),hideThreadsLabel:m("Hide threads")},messages:{attachedFilesLabel:m("Attached files"),copyMessageLabel:m("Copy message"),retryMessageLabel:m("Retry message"),retryButton:m("Retry"),startConversationLabel:m("Start a conversation"),suggestionPrefix:m("Select suggestion: "),loadingConversationLabel:m("Loading conversation…")},urlModal:{addUrlTitle:m("Add URL"),urlLabel:m("URL"),urlPlaceholder:m("Enter URL..."),loadFromUrlLabel:m("Load file from URL"),selectedFileLabel:m("Selected file"),loadingFromUrlLabel:m("Loading file from URL..."),cancelButton:m("Cancel"),addButton:m("Add")},artifactPanel:{copyCodeLabel:m("Copy code"),closePanelLabel:m("Close panel")},loading:{agentWorkingLabel:m("Agent is working...")}};let Ct=class extends((t=>B(F(N(H(t)))))(n)){constructor(){super(...arguments),this.requiredComponents=["nr-input","nr-button","nr-icon","nr-dropdown","nr-select","nr-modal","nr-popconfirm"],this.messages=[],this.currentInput="",this.isBotTyping=!1,this.isQueryRunning=!1,this.suggestions=[],this.chatStarted=!1,this.isRTL=!1,this.size=G.Medium,this.variant=K.Default,this.loadingIndicator=V.Dots,this.loadingText=m("Agent is working..."),this.disabled=!1,this.placeholder=m("Type your message..."),this.showSendButton=!0,this.autoScroll=!0,this.showThreads=!1,this.enableThreadCreation=!1,this.threads=[],this.mode="chat",this.boxed=!1,this.enableUrlSync=!1,this.showMessages=!0,this.enableFileUpload=!1,this.uploadedFiles=[],this.actionButtons=[],this.enableModuleSelection=!1,this.modules=[],this.selectedModules=[],this.moduleSelectionLabel=m("Select Modules"),this.enableArtifacts=!1,this.showAudioButton=!1,this.focused=!1,this.isArtifactPanelOpen=!1,this.selectedArtifact=null,this.isThreadSidebarOpen=!0,this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName="",this.isFilePreviewModalOpen=!1,this.previewFile=null,this._isDragging=!1,this._dragDepth=0,this.controllerUnsubscribes=[],this._audio=new Pt(this),this._audioMode="message",this._artifactResizeBound=!1,this.toggleThreadSidebar=()=>{this.isThreadSidebarOpen=!this.isThreadSidebarOpen}}get resolvedActionButtons(){var t;const e=null!==(t=this.actionButtons)&&void 0!==t?t:[];if(!this.enableFileUpload)return e;return e.some(t=>"attach"===(null==t?void 0:t.type))?e:[...e,{type:"attach",enabled:!0}]}get moduleSelectOptions(){return this.modules.map(t=>({value:t.id,label:t.name,icon:t.icon,disabled:!1===t.enabled,description:t.description}))}connectedCallback(){super.connectedCallback(),this.controller&&this.setupControllerIntegration(),this.setupUrlSync()}firstUpdated(){var t,e,i,n;null===(t=this.shadowRoot)||void 0===t||t.addEventListener("click",t=>{var e,i;const n=null===(i=(e=t.target).closest)||void 0===i?void 0:i.call(e,"[data-artifact-id]");if(n){const t=n.dataset.artifactId;t&&this.handleArtifactClick(t)}}),null===(e=this.shadowRoot)||void 0===e||e.addEventListener("nr-thread-edit",t=>{const e=t.detail;(null==e?void 0:e.threadId)&&(this._editingThreadId=e.threadId,this.requestUpdate(),this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".thread-item__rename-input");e&&(e.focus(),e.select())}))}),null===(i=this.shadowRoot)||void 0===i||i.addEventListener("click",t=>{var e,i;const n=null===(i=(e=t.target).closest)||void 0===i?void 0:i.call(e,"[data-selection-value]");if(n){const t=n.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}}),null===(n=this.shadowRoot)||void 0===n||n.addEventListener("keydown",t=>{var e,i,n,o;const s=t;if("Enter"!==s.key&&" "!==s.key)return;const r=null===(i=(e=s.target).closest)||void 0===i?void 0:i.call(e,"[data-artifact-id]");if(r){s.preventDefault();const t=r.dataset.artifactId;return void(t&&this.handleArtifactClick(t))}const a=null===(o=(n=s.target).closest)||void 0===o?void 0:o.call(n,"[data-selection-value]");if(a){s.preventDefault();const t=a.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}})}disconnectedCallback(){var t;super.disconnectedCallback(),this.controller&&this.cleanupControllerIntegration(),this.teardownUrlSync(),null===(t=this._artifactResizeCleanup)||void 0===t||t.call(this),this._artifactResizeBound=!1}updated(t){if(super.updated(t),t.has("controller")&&(this.cleanupControllerIntegration(),this.controller)){this.setupControllerIntegration();try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}this.enableUrlSync&&this.handleHashChange(),this.syncActiveThreadToController()}if(t.has("activeThreadId")&&this.syncActiveThreadToController(),t.has("enableUrlSync")&&(this.enableUrlSync?this.setupUrlSync():this.teardownUrlSync()),this.controller&&!t.has("controller")){if(t.has("messages")||t.has("suggestions")||t.has("threads"))try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}}t.has("messages")&&this.autoScroll&&this.messages.length>0&&this.scrollToLatestMessage(),this.updateArtifactPanelResize()}scrollToLatestMessage(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&(e.scrollTop=e.scrollHeight)})}setupControllerIntegration(){this.controller&&this.controllerUnsubscribes.push(this.controller.on("state:changed",this.handleControllerStateChange.bind(this)),this.controller.on("message:sent",this.handleControllerMessageSent.bind(this)),this.controller.on("message:received",this.handleControllerMessageReceived.bind(this)),this.controller.on("error",this.handleControllerError.bind(this)))}cleanupControllerIntegration(){if(this.controllerUnsubscribes.length)try{this.controllerUnsubscribes.forEach(t=>{try{t()}catch(t){}})}finally{this.controllerUnsubscribes=[]}}setupUrlSync(){this.enableUrlSync&&!this._hashChangeHandler&&(this._hashChangeHandler=this.handleHashChange.bind(this),window.addEventListener("hashchange",this._hashChangeHandler),this.handleHashChange())}teardownUrlSync(){this._hashChangeHandler&&(window.removeEventListener("hashchange",this._hashChangeHandler),this._hashChangeHandler=void 0)}handleHashChange(){const t=window.location.hash.match(/^#conversation\/(.+)$/);if(t){const e=decodeURIComponent(t[1]);e!==this.activeThreadId&&this.controller&&this.controller.switchThread(e)}}syncActiveThreadToController(){var t;if(!this.controller||!this.activeThreadId)return void(this._pendingThreadId=void 0);let e;try{e=this.controller.getState()}catch(t){e=null}if((null==e?void 0:e.currentThreadId)===this.activeThreadId)return void(this._pendingThreadId=void 0);if(null===(t=null==e?void 0:e.threads)||void 0===t?void 0:t.some(t=>t.id===this.activeThreadId)){this._pendingThreadId=void 0;try{this.controller.switchThread(this.activeThreadId)}catch(t){this._pendingThreadId=this.activeThreadId}}else this._pendingThreadId=this.activeThreadId}handleControllerStateChange(t){var e,i,n,o,s,r,a;if(t.messages&&(this.messages=t.messages),t.threads&&(this.threads=t.threads),t.suggestions&&t.suggestions.length>0&&(this.suggestions=t.suggestions),t.currentThreadId&&t.currentThreadId!==this.activeThreadId&&(this.activeThreadId=t.currentThreadId),this._pendingThreadId&&(null===(e=t.threads)||void 0===e?void 0:e.some(t=>t.id===this._pendingThreadId))){const t=this._pendingThreadId;this._pendingThreadId=void 0;try{null===(i=this.controller)||void 0===i||i.switchThread(t)}catch(e){this._pendingThreadId=t}}if(this.enableUrlSync&&t.currentThreadId){const e=`#conversation/${encodeURIComponent(t.currentThreadId)}`;window.location.hash!==e&&history.replaceState(null,"",e)}if(this.chatStarted=(null===(n=t.messages)||void 0===n?void 0:n.length)>0,this.isBotTyping=t.isTyping||!1,this.statusText=t.statusText,this.isQueryRunning=t.isProcessing||!1,t.uploadedFiles&&(this.uploadedFiles=t.uploadedFiles),this.enableArtifacts){const e=null===(o=t.messages)||void 0===o?void 0:o.some(t=>{var e,i;return(null===(i=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds)||void 0===i?void 0:i.length)>0});e||(this.isArtifactPanelOpen=!1,this.selectedArtifact=null)}if(this.enableArtifacts&&(null===(s=t.messages)||void 0===s?void 0:s.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),i=null===(r=null==e?void 0:e.metadata)||void 0===r?void 0:r.artifactIds;if(null==i?void 0:i.length){const t=i[i.length-1];if((null===(a=this.selectedArtifact)||void 0===a?void 0:a.id)!==t){const e=this.getArtifactPlugin(),i=null==e?void 0:e.getArtifact(t);i&&(this.selectedArtifact=i,this.isArtifactPanelOpen=!0)}}}}handleControllerMessageSent(t){this.isQueryRunning=!0,this.isBotTyping=!0}handleControllerMessageReceived(t){}handleControllerError(t){this.isQueryRunning=!1,this.isBotTyping=!1,console.error("Controller error:",t.error)}get resolvedI18n(){var t,e,i,n,o,s,r,a,l;const d=this.i18n;return{input:Object.assign(Object.assign({},Et.input),null!==(t=null==d?void 0:d.input)&&void 0!==t?t:{}),send:Object.assign(Object.assign({},Et.send),null!==(e=null==d?void 0:d.send)&&void 0!==e?e:{}),audio:Object.assign(Object.assign({},Et.audio),null!==(i=null==d?void 0:d.audio)&&void 0!==i?i:{}),modules:Object.assign(Object.assign({},Et.modules),null!==(n=null==d?void 0:d.modules)&&void 0!==n?n:{}),threads:Object.assign(Object.assign({},Et.threads),null!==(o=null==d?void 0:d.threads)&&void 0!==o?o:{}),messages:Object.assign(Object.assign({},Et.messages),null!==(s=null==d?void 0:d.messages)&&void 0!==s?s:{}),urlModal:Object.assign(Object.assign({},Et.urlModal),null!==(r=null==d?void 0:d.urlModal)&&void 0!==r?r:{}),artifactPanel:Object.assign(Object.assign({},Et.artifactPanel),null!==(a=null==d?void 0:d.artifactPanel)&&void 0!==a?a:{}),loading:Object.assign(Object.assign({},Et.loading),null!==(l=null==d?void 0:d.loading)&&void 0!==l?l:{})}}render(){var t;const e=this.resolvedI18n,n={boxed:this.boxed,showMessages:this.showMessages,welcomeMessage:this.welcomeMessage,isPendingThread:!!this._pendingThreadId,messages:this.messages,isTyping:this.isBotTyping,loadingIndicator:this.loadingIndicator,loadingText:this.statusText||this.loadingText,chatStarted:this.chatStarted,suggestions:this.suggestions,inputBox:{placeholder:this.placeholder,disabled:this.disabled||this.isQueryRunning,currentInput:this.currentInput,uploadedFiles:this.uploadedFiles,isQueryRunning:this.isQueryRunning,showSendButton:this.showSendButton,enableFileUpload:this.resolvedActionButtons.some(t=>"attach"===(null==t?void 0:t.type)&&!1!==(null==t?void 0:t.enabled)),fileUploadItems:[{id:"upload-file",label:"Upload File",icon:"upload"},{id:"upload-url",label:"Upload from URL",icon:"link"}],enableModuleSelection:this.enableModuleSelection,moduleOptions:this.moduleSelectOptions,selectedModules:this.selectedModules,moduleSelectionLabel:this.moduleSelectionLabel,renderModuleDisplay:this.renderModuleSelectedDisplay.bind(this),showAudioButton:this.showAudioButton,audioRecording:this._audio.state,audioMode:this._audioMode,i18n:e},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId,i18n:e}:void 0,enableFileUpload:this.enableFileUpload,isDragging:this._isDragging,i18n:e,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer(),i18n:e}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName,i18n:e}:void 0},o={message:{onRetry:this.handleRetry.bind(this),onRetryKeydown:()=>{},onCopy:this.handleCopyMessage.bind(this),onCopyKeydown:()=>{},onFileClick:this.handleFilePreview.bind(this)},suggestion:{onClick:this.handleSuggestionClick.bind(this),onKeydown:()=>{}},inputBox:{onInput:this.handleContentEditableInput.bind(this),onKeydown:this.handleKeyDown.bind(this),onFocus:this.handleInputFocus.bind(this),onBlur:this.handleInputBlur.bind(this),onSend:this.handleSendMessage.bind(this),onStop:this.handleStopQuery.bind(this),onSendKeydown:()=>{},onFileDropdownClick:this.handleFileDropdownClick.bind(this),onModuleChange:this.handleModuleSelectionChange.bind(this),onFileRemove:this.handleFileRemove.bind(this),onFileClick:this.handleFilePreview.bind(this),onAudioStart:this.handleAudioStart.bind(this),onAudioCancel:this.handleAudioCancel.bind(this),onAudioSend:this.handleAudioSend.bind(this)},threadSidebar:this.showThreads?{onCreateNew:()=>{var t;null===(t=this.controller)||void 0===t||t.createThread("New Chat")},onSelectThread:t=>{var e;t!==this.activeThreadId&&(this.enableUrlSync&&history.pushState(null,"",`#conversation/${encodeURIComponent(t)}`),null===(e=this.controller)||void 0===e||e.switchThread(t),this.dispatchEvent(new CustomEvent("nr-thread-change",{detail:{threadId:t},bubbles:!0,composed:!0})))},onDeleteThread:t=>{var e;null===(e=this.controller)||void 0===e||e.deleteThread(t)},onBookmarkThread:t=>{var e;null===(e=this.controller)||void 0===e||e.bookmarkThread(t)},onRenameThread:(t,e)=>{var i;null===(i=this.controller)||void 0===i||i.renameThread(t,e),this._editingThreadId=void 0}}:void 0,fileUploadArea:{onDragEnter:this.handleDragEnter.bind(this),onDragOver:this.handleDragOver.bind(this),onDragLeave:this.handleDragLeave.bind(this),onDrop:this.handleDrop.bind(this)},urlModal:this.isUrlModalOpen?{onClose:this.handleUrlModalClose.bind(this),onUrlInputChange:this.handleUrlInputChange.bind(this),onUrlInputKeydown:this.handleUrlInputKeydown.bind(this),onConfirm:this.handleUrlConfirm.bind(this),onAttachFile:this.handleUrlAttachFile.bind(this)}:void 0,artifactPanel:this.enableArtifacts?{onClose:this.handleArtifactPanelClose.bind(this),onCopy:this.handleArtifactCopy.bind(this)}:void 0,onToggleThreadSidebar:this.showThreads?this.toggleThreadSidebar.bind(this):void 0};return i`
|
|
2840
|
+
*/var Mt=function(t,e,i,n){for(var o,s=arguments.length,r=s<3?e:null===n?n=Object.getOwnPropertyDescriptor(e,i):n,a=t.length-1;a>=0;a--)(o=t[a])&&(r=(s<3?o(r):s>3?o(e,i,r):o(e,i))||r);return s>3&&r&&Object.defineProperty(e,i,r),r},Tt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})};const Et={input:{placeholder:m("Type your message..."),chatInputAriaLabel:m("Chat input"),attachButton:m("Attach"),attachFilesAriaLabel:m("Attach files"),removeFileLabel:m("Remove file"),uploadingLabel:m("Uploading"),uploadingProgress:m("Uploading…"),dropFilesHere:m("Drop files here to upload")},send:{sendButton:m("Send"),stopButton:m("Stop"),sendMessageLabel:m("Send message"),stopQueryLabel:m("Stop query")},audio:{recordSpeechLabel:m("Record speech to text"),sendVoiceMessageLabel:m("Send voice message"),cancelRecordingLabel:m("Cancel recording"),speechToTextLabel:m("Speech to text"),voiceMessageLabel:m("Voice message"),convertToTextLabel:m("Convert to text"),sendAsVoiceMessageLabel:m("Send as voice message")},modules:{moduleSelectionLabel:m("Select Modules"),moduleSearchPlaceholder:m("Search modules..."),moduleSelectAriaLabel:m("Select modules"),modulesSelectedSuffix:m("modules selected")},threads:{conversationsTitle:m("Conversations"),bookmarksLabel:m("Bookmarks"),allConversationsLabel:m("All Conversations"),noConversationsLabel:m("No conversations yet"),newChatTitle:m("New Chat"),newConversationLabel:m("New conversation"),removeBookmarkLabel:m("Remove bookmark"),bookmarkLabel:m("Bookmark"),renameLabel:m("Rename"),deleteLabel:m("Delete"),moreOptionsLabel:m("More options"),showThreadsLabel:m("Show threads"),hideThreadsLabel:m("Hide threads")},messages:{attachedFilesLabel:m("Attached files"),copyMessageLabel:m("Copy message"),retryMessageLabel:m("Retry message"),retryButton:m("Retry"),startConversationLabel:m("Start a conversation"),suggestionPrefix:m("Select suggestion: "),loadingConversationLabel:m("Loading conversation…"),showMoreLabel:m("Show more"),showLessLabel:m("Show less")},urlModal:{addUrlTitle:m("Add URL"),urlLabel:m("URL"),urlPlaceholder:m("Enter URL..."),loadFromUrlLabel:m("Load file from URL"),selectedFileLabel:m("Selected file"),loadingFromUrlLabel:m("Loading file from URL..."),cancelButton:m("Cancel"),addButton:m("Add")},artifactPanel:{copyCodeLabel:m("Copy code"),closePanelLabel:m("Close panel")},loading:{agentWorkingLabel:m("Agent is working...")}};let Ct=class extends((t=>B(F(N(H(t)))))(n)){constructor(){super(...arguments),this.requiredComponents=["nr-input","nr-button","nr-icon","nr-dropdown","nr-select","nr-modal","nr-popconfirm"],this.messages=[],this.currentInput="",this.isBotTyping=!1,this.isQueryRunning=!1,this.suggestions=[],this.chatStarted=!1,this.isRTL=!1,this.size=G.Medium,this.variant=K.Default,this.loadingIndicator=V.Dots,this.loadingText=m("Agent is working..."),this.disabled=!1,this.placeholder=m("Type your message..."),this.showSendButton=!0,this.autoScroll=!0,this.showThreads=!1,this.enableThreadCreation=!1,this.threads=[],this.mode="chat",this.boxed=!1,this.enableUrlSync=!1,this.showMessages=!0,this.enableFileUpload=!1,this.uploadedFiles=[],this.actionButtons=[],this.enableModuleSelection=!1,this.modules=[],this.selectedModules=[],this.moduleSelectionLabel=m("Select Modules"),this.enableArtifacts=!1,this.showAudioButton=!1,this.focused=!1,this.isArtifactPanelOpen=!1,this.selectedArtifact=null,this.isThreadSidebarOpen=!0,this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName="",this.isFilePreviewModalOpen=!1,this.previewFile=null,this._isDragging=!1,this._dragDepth=0,this.controllerUnsubscribes=[],this._audio=new Pt(this),this._audioMode="message",this._artifactResizeBound=!1,this._expandedMessageIds=new Set,this.messageCollapseThreshold=600,this.invertedScroll=!1,this.toggleThreadSidebar=()=>{this.isThreadSidebarOpen=!this.isThreadSidebarOpen}}get resolvedActionButtons(){var t;const e=null!==(t=this.actionButtons)&&void 0!==t?t:[];if(!this.enableFileUpload)return e;return e.some(t=>"attach"===(null==t?void 0:t.type))?e:[...e,{type:"attach",enabled:!0}]}get moduleSelectOptions(){return this.modules.map(t=>({value:t.id,label:t.name,icon:t.icon,disabled:!1===t.enabled,description:t.description}))}connectedCallback(){super.connectedCallback(),this.controller&&this.setupControllerIntegration(),this.setupUrlSync()}firstUpdated(){var t,e,i,n,o;null===(t=this.shadowRoot)||void 0===t||t.addEventListener("click",t=>{var e,i;const n=null===(i=(e=t.target).closest)||void 0===i?void 0:i.call(e,"[data-artifact-id]");if(n){const t=n.dataset.artifactId;t&&this.handleArtifactClick(t)}}),null===(e=this.shadowRoot)||void 0===e||e.addEventListener("nr-thread-edit",t=>{const e=t.detail;(null==e?void 0:e.threadId)&&(this._editingThreadId=e.threadId,this.requestUpdate(),this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".thread-item__rename-input");e&&(e.focus(),e.select())}))}),null===(i=this.shadowRoot)||void 0===i||i.addEventListener("click",t=>{var e,i;const n=null===(i=(e=t.target).closest)||void 0===i?void 0:i.call(e,"[data-selection-value]");if(n){const t=n.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}}),null===(n=this.shadowRoot)||void 0===n||n.addEventListener("click",t=>{var e,i;const n=null===(i=(e=t.target).closest)||void 0===i?void 0:i.call(e,"[data-message-toggle]");if(n){const t=n.dataset.messageToggle;if(t){const e=new Set(this._expandedMessageIds);e.has(t)?e.delete(t):e.add(t),this._expandedMessageIds=e}}}),null===(o=this.shadowRoot)||void 0===o||o.addEventListener("keydown",t=>{var e,i,n,o;const s=t;if("Enter"!==s.key&&" "!==s.key)return;const r=null===(i=(e=s.target).closest)||void 0===i?void 0:i.call(e,"[data-artifact-id]");if(r){s.preventDefault();const t=r.dataset.artifactId;return void(t&&this.handleArtifactClick(t))}const a=null===(o=(n=s.target).closest)||void 0===o?void 0:o.call(n,"[data-selection-value]");if(a){s.preventDefault();const t=a.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}})}disconnectedCallback(){var t;super.disconnectedCallback(),this.controller&&this.cleanupControllerIntegration(),this.teardownUrlSync(),null===(t=this._artifactResizeCleanup)||void 0===t||t.call(this),this._artifactResizeBound=!1}updated(t){if(super.updated(t),t.has("controller")&&(this.cleanupControllerIntegration(),this.controller)){this.setupControllerIntegration();try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}this.enableUrlSync&&this.handleHashChange(),this.syncActiveThreadToController()}if(t.has("activeThreadId")&&this.syncActiveThreadToController(),t.has("enableUrlSync")&&(this.enableUrlSync?this.setupUrlSync():this.teardownUrlSync()),this.controller&&!t.has("controller")){if(t.has("messages")||t.has("suggestions")||t.has("threads"))try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}}t.has("messages")&&this.autoScroll&&!this.invertedScroll&&this.messages.length>0&&this.scrollToLatestMessage(),this.updateArtifactPanelResize()}scrollToLatestMessage(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&(e.scrollTop=e.scrollHeight)})}setupControllerIntegration(){this.controller&&this.controllerUnsubscribes.push(this.controller.on("state:changed",this.handleControllerStateChange.bind(this)),this.controller.on("message:sent",this.handleControllerMessageSent.bind(this)),this.controller.on("message:received",this.handleControllerMessageReceived.bind(this)),this.controller.on("error",this.handleControllerError.bind(this)))}cleanupControllerIntegration(){if(this.controllerUnsubscribes.length)try{this.controllerUnsubscribes.forEach(t=>{try{t()}catch(t){}})}finally{this.controllerUnsubscribes=[]}}setupUrlSync(){this.enableUrlSync&&!this._hashChangeHandler&&(this._hashChangeHandler=this.handleHashChange.bind(this),window.addEventListener("hashchange",this._hashChangeHandler),this.handleHashChange())}teardownUrlSync(){this._hashChangeHandler&&(window.removeEventListener("hashchange",this._hashChangeHandler),this._hashChangeHandler=void 0)}handleHashChange(){const t=window.location.hash.match(/^#conversation\/(.+)$/);if(t){const e=decodeURIComponent(t[1]);e!==this.activeThreadId&&this.controller&&this.controller.switchThread(e)}}syncActiveThreadToController(){var t;if(!this.controller||!this.activeThreadId)return void(this._pendingThreadId=void 0);let e;try{e=this.controller.getState()}catch(t){e=null}if((null==e?void 0:e.currentThreadId)===this.activeThreadId)return void(this._pendingThreadId=void 0);if(null===(t=null==e?void 0:e.threads)||void 0===t?void 0:t.some(t=>t.id===this.activeThreadId)){this._pendingThreadId=void 0;try{this.controller.switchThread(this.activeThreadId)}catch(t){this._pendingThreadId=this.activeThreadId}}else this._pendingThreadId=this.activeThreadId}handleControllerStateChange(t){var e,i,n,o,s,r,a;if(t.messages&&(this.messages=t.messages),t.threads&&(this.threads=t.threads),t.suggestions&&t.suggestions.length>0&&(this.suggestions=t.suggestions),t.currentThreadId&&t.currentThreadId!==this.activeThreadId&&(this.activeThreadId=t.currentThreadId),this._pendingThreadId&&(null===(e=t.threads)||void 0===e?void 0:e.some(t=>t.id===this._pendingThreadId))){const t=this._pendingThreadId;this._pendingThreadId=void 0;try{null===(i=this.controller)||void 0===i||i.switchThread(t)}catch(e){this._pendingThreadId=t}}if(this.enableUrlSync&&t.currentThreadId){const e=`#conversation/${encodeURIComponent(t.currentThreadId)}`;window.location.hash!==e&&history.replaceState(null,"",e)}if(this.chatStarted=(null===(n=t.messages)||void 0===n?void 0:n.length)>0,this.isBotTyping=t.isTyping||!1,this.statusText=t.statusText,this.isQueryRunning=t.isProcessing||!1,t.uploadedFiles&&(this.uploadedFiles=t.uploadedFiles),this.enableArtifacts){const e=null===(o=t.messages)||void 0===o?void 0:o.some(t=>{var e,i;return(null===(i=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds)||void 0===i?void 0:i.length)>0});e||(this.isArtifactPanelOpen=!1,this.selectedArtifact=null)}if(this.enableArtifacts&&(null===(s=t.messages)||void 0===s?void 0:s.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),i=null===(r=null==e?void 0:e.metadata)||void 0===r?void 0:r.artifactIds;if(null==i?void 0:i.length){const t=i[i.length-1];if((null===(a=this.selectedArtifact)||void 0===a?void 0:a.id)!==t){const e=this.getArtifactPlugin(),i=null==e?void 0:e.getArtifact(t);i&&(this.selectedArtifact=i,this.isArtifactPanelOpen=!0)}}}}handleControllerMessageSent(t){this.isQueryRunning=!0,this.isBotTyping=!0}handleControllerMessageReceived(t){}handleControllerError(t){this.isQueryRunning=!1,this.isBotTyping=!1,console.error("Controller error:",t.error)}get resolvedI18n(){var t,e,i,n,o,s,r,a,l;const d=this.i18n;return{input:Object.assign(Object.assign({},Et.input),null!==(t=null==d?void 0:d.input)&&void 0!==t?t:{}),send:Object.assign(Object.assign({},Et.send),null!==(e=null==d?void 0:d.send)&&void 0!==e?e:{}),audio:Object.assign(Object.assign({},Et.audio),null!==(i=null==d?void 0:d.audio)&&void 0!==i?i:{}),modules:Object.assign(Object.assign({},Et.modules),null!==(n=null==d?void 0:d.modules)&&void 0!==n?n:{}),threads:Object.assign(Object.assign({},Et.threads),null!==(o=null==d?void 0:d.threads)&&void 0!==o?o:{}),messages:Object.assign(Object.assign({},Et.messages),null!==(s=null==d?void 0:d.messages)&&void 0!==s?s:{}),urlModal:Object.assign(Object.assign({},Et.urlModal),null!==(r=null==d?void 0:d.urlModal)&&void 0!==r?r:{}),artifactPanel:Object.assign(Object.assign({},Et.artifactPanel),null!==(a=null==d?void 0:d.artifactPanel)&&void 0!==a?a:{}),loading:Object.assign(Object.assign({},Et.loading),null!==(l=null==d?void 0:d.loading)&&void 0!==l?l:{})}}render(){var t;const e=this.resolvedI18n,n={boxed:this.boxed,showMessages:this.showMessages,welcomeMessage:this.welcomeMessage,isPendingThread:!!this._pendingThreadId,invertedScroll:this.invertedScroll,messages:this.messages,isTyping:this.isBotTyping,loadingIndicator:this.loadingIndicator,loadingText:this.statusText||this.loadingText,chatStarted:this.chatStarted,suggestions:this.suggestions,inputBox:{placeholder:this.placeholder,disabled:this.disabled||this.isQueryRunning,currentInput:this.currentInput,uploadedFiles:this.uploadedFiles,isQueryRunning:this.isQueryRunning,showSendButton:this.showSendButton,enableFileUpload:this.resolvedActionButtons.some(t=>"attach"===(null==t?void 0:t.type)&&!1!==(null==t?void 0:t.enabled)),fileUploadItems:[{id:"upload-file",label:"Upload File",icon:"upload"},{id:"upload-url",label:"Upload from URL",icon:"link"}],enableModuleSelection:this.enableModuleSelection,moduleOptions:this.moduleSelectOptions,selectedModules:this.selectedModules,moduleSelectionLabel:this.moduleSelectionLabel,renderModuleDisplay:this.renderModuleSelectedDisplay.bind(this),showAudioButton:this.showAudioButton,audioRecording:this._audio.state,audioMode:this._audioMode,i18n:e},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId,i18n:e}:void 0,enableFileUpload:this.enableFileUpload,isDragging:this._isDragging,i18n:e,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer(),i18n:e}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName,i18n:e}:void 0},o={message:{onRetry:this.handleRetry.bind(this),onRetryKeydown:()=>{},onCopy:this.handleCopyMessage.bind(this),onCopyKeydown:()=>{},onFileClick:this.handleFilePreview.bind(this),collapseThreshold:this.messageCollapseThreshold,isExpanded:t=>this._expandedMessageIds.has(t)},suggestion:{onClick:this.handleSuggestionClick.bind(this),onKeydown:()=>{}},inputBox:{onInput:this.handleContentEditableInput.bind(this),onKeydown:this.handleKeyDown.bind(this),onFocus:this.handleInputFocus.bind(this),onBlur:this.handleInputBlur.bind(this),onSend:this.handleSendMessage.bind(this),onStop:this.handleStopQuery.bind(this),onSendKeydown:()=>{},onFileDropdownClick:this.handleFileDropdownClick.bind(this),onModuleChange:this.handleModuleSelectionChange.bind(this),onFileRemove:this.handleFileRemove.bind(this),onFileClick:this.handleFilePreview.bind(this),onAudioStart:this.handleAudioStart.bind(this),onAudioCancel:this.handleAudioCancel.bind(this),onAudioSend:this.handleAudioSend.bind(this)},threadSidebar:this.showThreads?{onCreateNew:()=>{var t;null===(t=this.controller)||void 0===t||t.createThread("New Chat")},onSelectThread:t=>{var e;t!==this.activeThreadId&&(this.enableUrlSync&&history.pushState(null,"",`#conversation/${encodeURIComponent(t)}`),null===(e=this.controller)||void 0===e||e.switchThread(t),this.dispatchEvent(new CustomEvent("nr-thread-change",{detail:{threadId:t},bubbles:!0,composed:!0})))},onDeleteThread:t=>{var e;null===(e=this.controller)||void 0===e||e.deleteThread(t)},onBookmarkThread:t=>{var e;null===(e=this.controller)||void 0===e||e.bookmarkThread(t)},onRenameThread:(t,e)=>{var i;null===(i=this.controller)||void 0===i||i.renameThread(t,e),this._editingThreadId=void 0}}:void 0,fileUploadArea:{onDragEnter:this.handleDragEnter.bind(this),onDragOver:this.handleDragOver.bind(this),onDragLeave:this.handleDragLeave.bind(this),onDrop:this.handleDrop.bind(this)},urlModal:this.isUrlModalOpen?{onClose:this.handleUrlModalClose.bind(this),onUrlInputChange:this.handleUrlInputChange.bind(this),onUrlInputKeydown:this.handleUrlInputKeydown.bind(this),onConfirm:this.handleUrlConfirm.bind(this),onAttachFile:this.handleUrlAttachFile.bind(this)}:void 0,artifactPanel:this.enableArtifacts?{onClose:this.handleArtifactPanelClose.bind(this),onCopy:this.handleArtifactCopy.bind(this)}:void 0,onToggleThreadSidebar:this.showThreads?this.toggleThreadSidebar.bind(this):void 0};return i`
|
|
2767
2841
|
<div
|
|
2768
2842
|
class="chat-container ${a({"chat-container--with-threads":this.showThreads,"chat-container--disabled":this.disabled,"chat-container--focused":this.focused,"chat-container--boxed":this.boxed})}"
|
|
2769
2843
|
dir=${this.isRTL?"rtl":"ltr"}
|
|
@@ -2776,7 +2850,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2776
2850
|
${$t(n,o)}
|
|
2777
2851
|
</div>
|
|
2778
2852
|
|
|
2779
|
-
${
|
|
2853
|
+
${yt({isOpen:this.isFilePreviewModalOpen,file:this.previewFile},{onClose:this.handleFilePreviewModalClose.bind(this)})}
|
|
2780
2854
|
`}renderModuleSelectedDisplay(){const t=this.selectedModules.length;if(0===t)return i`<span class="module-display-placeholder">${this.moduleSelectionLabel}</span>`;if(1===t){const t=this.modules.find(t=>t.id===this.selectedModules[0]);return i`
|
|
2781
2855
|
<span class="module-display-single">
|
|
2782
2856
|
${(null==t?void 0:t.icon)?i`<nr-icon name="${t.icon}" size="small"></nr-icon>`:e}
|
|
@@ -2786,7 +2860,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2786
2860
|
<span class="module-display-multiple">
|
|
2787
2861
|
${t} ${this.resolvedI18n.modules.modulesSelectedSuffix}
|
|
2788
2862
|
</span>
|
|
2789
|
-
`}handleContentEditableInput(t){const e=t.target.textContent||"";this.currentInput=e,this.dispatchEventWithMetadata("nr-chatbot-input-changed",{metadata:{value:e}})}handleInputFocus(t){this.focused=!0,this.dispatchEventWithMetadata("nr-chatbot-input-focused",{metadata:{event:t}})}handleInputBlur(t){this.focused=!1,this.dispatchEventWithMetadata("nr-chatbot-input-blurred",{metadata:{event:t}})}clearInput(){var t;this.currentInput="";const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&(e.textContent="")}focusInput(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&e.focus()}handleAudioStart(t){this._audioMode=t,this._audio.start()}handleAudioCancel(){this._audio.cancel()}handleAudioSend(){return Tt(this,void 0,void 0,function*(){var t;const e=yield this._audio.stop();if(!e)return;const i=this._audioMode;null===(t=this.onAudioRecorded)||void 0===t||t.call(this,e.blob,e.mimeType,e.duration,i),this.dispatchEvent(new CustomEvent("nr-chatbot-audio-recorded",{detail:{blob:e.blob,mimeType:e.mimeType,duration:e.duration,mode:i},bubbles:!0,composed:!0}))})}handleKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendMessage())}handleSendMessage(){if(!this.currentInput.trim()||this.disabled)return;if(!this.controller)return void console.warn("nr-chatbot: No controller is attached; message will not be sent.");const t=this.uploadedFiles&&this.uploadedFiles.length>0?[...this.uploadedFiles]:void 0;this.controller.sendMessage(this.currentInput.trim(),{files:t,metadata:{selectedModules:this.selectedModules}}),this.clearInput(),this.chatStarted=!0,this.dispatchEventWithMetadata("nr-chatbot-message-sent",{metadata:{text:this.currentInput}})}handleStopQuery(){var t;try{null===(t=this.controller)||void 0===t||t.stop()}catch(t){console.warn("nr-chatbot: stop failed",t)}this.dispatchEventWithMetadata("nr-chatbot-query-stopped",{metadata:{action:"stop"}})}handleRetry(t){t.text&&(this.currentInput=t.text,this.handleSendMessage())}handleCopyMessage(t){const e=t.text;if(!e)return;const i=()=>{this.dispatchEventWithMetadata("nr-chatbot-message-copied",{metadata:{messageId:t.id}})};navigator.clipboard?navigator.clipboard.writeText(e).then(i).catch(()=>{this.copyViaFallback(e,i)}):this.copyViaFallback(e,i)}copyViaFallback(t,e){const i=document.createElement("textarea");i.value=t,i.style.position="fixed",i.style.left="-9999px",i.style.top="-9999px",document.body.appendChild(i),i.focus(),i.select();try{document.execCommand("copy"),e()}catch(t){}i.remove()}handleSuggestionClick(t){this.currentInput=t.text,this.handleSendMessage(),this.dispatchEventWithMetadata("nr-chatbot-suggestion-clicked",{metadata:{suggestion:t}})}handleModuleSelectionChange(t){const e=t.detail.value;this.selectedModules=e,this.dispatchEventWithMetadata("nr-chatbot-modules-selected",{metadata:{modules:e}})}handleFileDropdownClick(t){const e=t.detail.item.id;"upload-file"===e?this.openFileDialog():"upload-url"===e&&this.openUrlModal()}openFileDialog(){const t=document.createElement("input");t.type="file",t.multiple=!0,t.accept="image/*,application/pdf,text/*,video/*,audio/*",t.addEventListener("change",t=>Tt(this,void 0,void 0,function*(){var e;const i=t.target;if(i.files&&i.files.length>0){const t=Array.from(i.files);yield null===(e=this.controller)||void 0===e?void 0:e.uploadFiles(t)}})),t.click()}openUrlModal(){this.isUrlModalOpen=!0,this.urlInput="",this.urlModalError="",this.selectedUrlFileName=""}handleUrlModalClose(){this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName=""}handleUrlInputChange(t){const e=t.target;this.urlInput=e.value,this.urlModalError=""}handleUrlInputKeydown(t){"Enter"===t.key&&(t.preventDefault(),this.handleUrlAttachFile())}handleUrlConfirm(){this.handleUrlModalClose()}handleUrlAttachFile(){return Tt(this,void 0,void 0,function*(){if(this.urlInput.trim()){this.isUrlLoading=!0,this.urlModalError="";try{const t=yield fetch(this.urlInput);if(!t.ok)throw new Error(`Failed to fetch file: ${t.statusText}`);const e=yield t.blob(),i=this.urlInput.split("/").pop()||"downloaded-file",n=new File([e],i,{type:e.type});this.selectedUrlFileName=i,this.controller&&(yield this.controller.uploadFiles([n])),this.isUrlLoading=!1,setTimeout(()=>{this.handleUrlModalClose()},1e3)}catch(t){this.isUrlLoading=!1,this.urlModalError=t instanceof Error?t.message:"Failed to load file from URL"}}else this.urlModalError="Please enter a URL"})}handleFileRemove(t){var e;null===(e=this.controller)||void 0===e||e.removeFile(t)}dragHasFiles(t){var e;const i=null===(e=t.dataTransfer)||void 0===e?void 0:e.types;if(!i)return!1;for(let t=0;t<i.length;t++)if("Files"===i[t])return!0;return!1}handleDragEnter(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),this._dragDepth++,this._isDragging=!0)}handleDragOver(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))}handleDragLeave(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),this._dragDepth=Math.max(0,this._dragDepth-1),0===this._dragDepth&&(this._isDragging=!1))}handleDrop(t){return Tt(this,void 0,void 0,function*(){var e,i;if(!this.enableFileUpload||this.disabled)return;t.preventDefault(),this._dragDepth=0,this._isDragging=!1;const n=null===(e=t.dataTransfer)||void 0===e?void 0:e.files;n&&0!==n.length&&(yield null===(i=this.controller)||void 0===i?void 0:i.uploadFiles(Array.from(n)))})}handleFilePreview(t){this.previewFile=t,this.isFilePreviewModalOpen=!0}handleArtifactClick(t){if(!this.enableArtifacts||!this.controller)return;const e=this.getArtifactPlugin();if(!e)return;const i=e.getArtifact(t);i&&(this.selectedArtifact=i,this.isArtifactPanelOpen=!0)}handleArtifactPanelClose(){this.isArtifactPanelOpen=!1,this.selectedArtifact=null}updateArtifactPanelResize(){var t,e,i;const n=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".artifact-panel__resize-handle"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".artifact-panel");if(!n||!o)return null===(i=this._artifactResizeCleanup)||void 0===i||i.call(this),void(this._artifactResizeBound=!1);if(this._artifactResizeBound)return;this._artifactResizeBound=!0;let s=!1,r=0,a=0;const l=t=>{if(!s)return;const e=t.clientX-r,i=o.parentElement,n=i?.85*i.getBoundingClientRect().width:1200,l=Number.parseInt(getComputedStyle(o).minWidth,10)||300,d=Math.max(l,Math.min(a-e,n));o.style.width=`${d}px`},d=()=>{s&&(s=!1,n.classList.remove("artifact-panel__resize-handle--active"),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d))},c=t=>{t.preventDefault(),s=!0,r=t.clientX,a=o.getBoundingClientRect().width,n.classList.add("artifact-panel__resize-handle--active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)};n.addEventListener("mousedown",c),this._artifactResizeCleanup=()=>{n.removeEventListener("mousedown",c),d()}}handleArtifactCopy(t){const e=t.content;e&&(navigator.clipboard?navigator.clipboard.writeText(e).catch(()=>{this.copyViaFallback(e,()=>{})}):this.copyViaFallback(e,()=>{}))}getArtifactPlugin(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;return e&&"function"==typeof e.get?e.get("artifact"):void 0}catch(t){return}}getPluginArtifactRenderer(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;if(!e||"function"!=typeof e.values)return;for(const t of e.values())if("function"==typeof t.renderArtifactContent)return e=>{const n=t.renderArtifactContent(e);if(n)return i`${l(n)}`};return}catch(t){return}}handleFilePreviewModalClose(){this.isFilePreviewModalOpen=!1,this.previewFile=null}addMessage(t){var e;const i=Object.assign({id:t.id||`msg-${Date.now()}`,sender:t.sender||q.User,text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t);return null===(e=this.controller)||void 0===e||e.addMessage(i),this.chatStarted=!0,i}clearMessages(){this.messages=[],this.chatStarted=!1}};Ct.useShadowDom=!0,Ct.styles=L,Mt([o({type:Array})],Ct.prototype,"messages",void 0),Mt([o({type:String})],Ct.prototype,"currentInput",void 0),Mt([o({type:Boolean})],Ct.prototype,"isBotTyping",void 0),Mt([o({type:Boolean})],Ct.prototype,"isQueryRunning",void 0),Mt([o({type:Array})],Ct.prototype,"suggestions",void 0),Mt([o({type:Boolean})],Ct.prototype,"chatStarted",void 0),Mt([o({type:Boolean})],Ct.prototype,"isRTL",void 0),Mt([o({type:String})],Ct.prototype,"size",void 0),Mt([o({type:String})],Ct.prototype,"variant",void 0),Mt([o({type:String})],Ct.prototype,"loadingIndicator",void 0),Mt([o({type:String})],Ct.prototype,"loadingText",void 0),Mt([o({type:Boolean})],Ct.prototype,"disabled",void 0),Mt([o({type:String})],Ct.prototype,"placeholder",void 0),Mt([o({type:Object})],Ct.prototype,"i18n",void 0),Mt([o({type:Boolean})],Ct.prototype,"showSendButton",void 0),Mt([o({type:Boolean})],Ct.prototype,"autoScroll",void 0),Mt([o({type:Boolean})],Ct.prototype,"showThreads",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableThreadCreation",void 0),Mt([o({type:Array})],Ct.prototype,"threads",void 0),Mt([o({type:String,attribute:"active-thread-id"})],Ct.prototype,"activeThreadId",void 0),Mt([o({type:String})],Ct.prototype,"mode",void 0),Mt([o({type:Boolean,reflect:!0})],Ct.prototype,"boxed",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableUrlSync",void 0),Mt([o({type:Boolean})],Ct.prototype,"showMessages",void 0),Mt([o({type:String,attribute:"welcome-message"})],Ct.prototype,"welcomeMessage",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableFileUpload",void 0),Mt([o({type:Array})],Ct.prototype,"uploadedFiles",void 0),Mt([o({type:Array})],Ct.prototype,"actionButtons",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableModuleSelection",void 0),Mt([o({type:Array})],Ct.prototype,"modules",void 0),Mt([o({type:Array})],Ct.prototype,"selectedModules",void 0),Mt([o({type:String})],Ct.prototype,"moduleSelectionLabel",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableArtifacts",void 0),Mt([o({type:Boolean,attribute:"show-audio-button"})],Ct.prototype,"showAudioButton",void 0),Mt([o({type:Function})],Ct.prototype,"onAudioRecorded",void 0),Mt([o({type:Function})],Ct.prototype,"renderArtifactContent",void 0),Mt([o({type:Object})],Ct.prototype,"controller",void 0),Mt([s()],Ct.prototype,"statusText",void 0),Mt([s()],Ct.prototype,"focused",void 0),Mt([s()],Ct.prototype,"isArtifactPanelOpen",void 0),Mt([s()],Ct.prototype,"selectedArtifact",void 0),Mt([s()],Ct.prototype,"isThreadSidebarOpen",void 0),Mt([s()],Ct.prototype,"_editingThreadId",void 0),Mt([s()],Ct.prototype,"isUrlModalOpen",void 0),Mt([s()],Ct.prototype,"urlInput",void 0),Mt([s()],Ct.prototype,"urlModalError",void 0),Mt([s()],Ct.prototype,"isUrlLoading",void 0),Mt([s()],Ct.prototype,"selectedUrlFileName",void 0),Mt([s()],Ct.prototype,"isFilePreviewModalOpen",void 0),Mt([s()],Ct.prototype,"previewFile",void 0),Mt([s()],Ct.prototype,"_isDragging",void 0),Mt([s()],Ct.prototype,"_pendingThreadId",void 0),Ct=Mt([(t,e)=>(t.addInitializer(b),t),r("nr-chatbot")],Ct);
|
|
2863
|
+
`}handleContentEditableInput(t){const e=t.target.textContent||"";this.currentInput=e,this.dispatchEventWithMetadata("nr-chatbot-input-changed",{metadata:{value:e}})}handleInputFocus(t){this.focused=!0,this.dispatchEventWithMetadata("nr-chatbot-input-focused",{metadata:{event:t}})}handleInputBlur(t){this.focused=!1,this.dispatchEventWithMetadata("nr-chatbot-input-blurred",{metadata:{event:t}})}clearInput(){var t;this.currentInput="";const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&(e.textContent="")}focusInput(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&e.focus()}handleAudioStart(t){this._audioMode=t,this._audio.start()}handleAudioCancel(){this._audio.cancel()}handleAudioSend(){return Tt(this,void 0,void 0,function*(){var t;const e=yield this._audio.stop();if(!e)return;const i=this._audioMode;null===(t=this.onAudioRecorded)||void 0===t||t.call(this,e.blob,e.mimeType,e.duration,i),this.dispatchEvent(new CustomEvent("nr-chatbot-audio-recorded",{detail:{blob:e.blob,mimeType:e.mimeType,duration:e.duration,mode:i},bubbles:!0,composed:!0}))})}handleKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendMessage())}handleSendMessage(){if(!this.currentInput.trim()||this.disabled)return;if(!this.controller)return void console.warn("nr-chatbot: No controller is attached; message will not be sent.");const t=this.uploadedFiles&&this.uploadedFiles.length>0?[...this.uploadedFiles]:void 0;this.controller.sendMessage(this.currentInput.trim(),{files:t,metadata:{selectedModules:this.selectedModules}}),this.clearInput(),this.chatStarted=!0,this.dispatchEventWithMetadata("nr-chatbot-message-sent",{metadata:{text:this.currentInput}})}handleStopQuery(){var t;try{null===(t=this.controller)||void 0===t||t.stop()}catch(t){console.warn("nr-chatbot: stop failed",t)}this.dispatchEventWithMetadata("nr-chatbot-query-stopped",{metadata:{action:"stop"}})}handleRetry(t){t.text&&(this.currentInput=t.text,this.handleSendMessage())}handleCopyMessage(t){const e=t.text;if(!e)return;const i=()=>{this.dispatchEventWithMetadata("nr-chatbot-message-copied",{metadata:{messageId:t.id}})};navigator.clipboard?navigator.clipboard.writeText(e).then(i).catch(()=>{this.copyViaFallback(e,i)}):this.copyViaFallback(e,i)}copyViaFallback(t,e){const i=document.createElement("textarea");i.value=t,i.style.position="fixed",i.style.left="-9999px",i.style.top="-9999px",document.body.appendChild(i),i.focus(),i.select();try{document.execCommand("copy"),e()}catch(t){}i.remove()}handleSuggestionClick(t){this.currentInput=t.text,this.handleSendMessage(),this.dispatchEventWithMetadata("nr-chatbot-suggestion-clicked",{metadata:{suggestion:t}})}handleModuleSelectionChange(t){const e=t.detail.value;this.selectedModules=e,this.dispatchEventWithMetadata("nr-chatbot-modules-selected",{metadata:{modules:e}})}handleFileDropdownClick(t){const e=t.detail.item.id;"upload-file"===e?this.openFileDialog():"upload-url"===e&&this.openUrlModal()}openFileDialog(){const t=document.createElement("input");t.type="file",t.multiple=!0,t.accept="image/*,application/pdf,text/*,video/*,audio/*",t.addEventListener("change",t=>Tt(this,void 0,void 0,function*(){var e;const i=t.target;if(i.files&&i.files.length>0){const t=Array.from(i.files);yield null===(e=this.controller)||void 0===e?void 0:e.uploadFiles(t)}})),t.click()}openUrlModal(){this.isUrlModalOpen=!0,this.urlInput="",this.urlModalError="",this.selectedUrlFileName=""}handleUrlModalClose(){this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName=""}handleUrlInputChange(t){const e=t.target;this.urlInput=e.value,this.urlModalError=""}handleUrlInputKeydown(t){"Enter"===t.key&&(t.preventDefault(),this.handleUrlAttachFile())}handleUrlConfirm(){this.handleUrlModalClose()}handleUrlAttachFile(){return Tt(this,void 0,void 0,function*(){if(this.urlInput.trim()){this.isUrlLoading=!0,this.urlModalError="";try{const t=yield fetch(this.urlInput);if(!t.ok)throw new Error(`Failed to fetch file: ${t.statusText}`);const e=yield t.blob(),i=this.urlInput.split("/").pop()||"downloaded-file",n=new File([e],i,{type:e.type});this.selectedUrlFileName=i,this.controller&&(yield this.controller.uploadFiles([n])),this.isUrlLoading=!1,setTimeout(()=>{this.handleUrlModalClose()},1e3)}catch(t){this.isUrlLoading=!1,this.urlModalError=t instanceof Error?t.message:"Failed to load file from URL"}}else this.urlModalError="Please enter a URL"})}handleFileRemove(t){var e;null===(e=this.controller)||void 0===e||e.removeFile(t)}dragHasFiles(t){var e;const i=null===(e=t.dataTransfer)||void 0===e?void 0:e.types;if(!i)return!1;for(let t=0;t<i.length;t++)if("Files"===i[t])return!0;return!1}handleDragEnter(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),this._dragDepth++,this._isDragging=!0)}handleDragOver(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="copy"))}handleDragLeave(t){this.enableFileUpload&&!this.disabled&&this.dragHasFiles(t)&&(t.preventDefault(),this._dragDepth=Math.max(0,this._dragDepth-1),0===this._dragDepth&&(this._isDragging=!1))}handleDrop(t){return Tt(this,void 0,void 0,function*(){var e,i;if(!this.enableFileUpload||this.disabled)return;t.preventDefault(),this._dragDepth=0,this._isDragging=!1;const n=null===(e=t.dataTransfer)||void 0===e?void 0:e.files;n&&0!==n.length&&(yield null===(i=this.controller)||void 0===i?void 0:i.uploadFiles(Array.from(n)))})}handleFilePreview(t){this.previewFile=t,this.isFilePreviewModalOpen=!0}handleArtifactClick(t){if(!this.enableArtifacts||!this.controller)return;const e=this.getArtifactPlugin();if(!e)return;const i=e.getArtifact(t);i&&(this.selectedArtifact=i,this.isArtifactPanelOpen=!0)}handleArtifactPanelClose(){this.isArtifactPanelOpen=!1,this.selectedArtifact=null}updateArtifactPanelResize(){var t,e,i;const n=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".artifact-panel__resize-handle"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".artifact-panel");if(!n||!o)return null===(i=this._artifactResizeCleanup)||void 0===i||i.call(this),void(this._artifactResizeBound=!1);if(this._artifactResizeBound)return;this._artifactResizeBound=!0;let s=!1,r=0,a=0;const l=t=>{if(!s)return;const e=t.clientX-r,i=o.parentElement,n=i?.85*i.getBoundingClientRect().width:1200,l=Number.parseInt(getComputedStyle(o).minWidth,10)||300,d=Math.max(l,Math.min(a-e,n));o.style.width=`${d}px`},d=()=>{s&&(s=!1,n.classList.remove("artifact-panel__resize-handle--active"),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d))},c=t=>{t.preventDefault(),s=!0,r=t.clientX,a=o.getBoundingClientRect().width,n.classList.add("artifact-panel__resize-handle--active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)};n.addEventListener("mousedown",c),this._artifactResizeCleanup=()=>{n.removeEventListener("mousedown",c),d()}}handleArtifactCopy(t){const e=t.content;e&&(navigator.clipboard?navigator.clipboard.writeText(e).catch(()=>{this.copyViaFallback(e,()=>{})}):this.copyViaFallback(e,()=>{}))}getArtifactPlugin(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;return e&&"function"==typeof e.get?e.get("artifact"):void 0}catch(t){return}}getPluginArtifactRenderer(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;if(!e||"function"!=typeof e.values)return;for(const t of e.values())if("function"==typeof t.renderArtifactContent)return e=>{const n=t.renderArtifactContent(e);if(n)return i`${l(n)}`};return}catch(t){return}}handleFilePreviewModalClose(){this.isFilePreviewModalOpen=!1,this.previewFile=null}addMessage(t){var e;const i=Object.assign({id:t.id||`msg-${Date.now()}`,sender:t.sender||q.User,text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t);return null===(e=this.controller)||void 0===e||e.addMessage(i),this.chatStarted=!0,i}clearMessages(){this.messages=[],this.chatStarted=!1}};Ct.useShadowDom=!0,Ct.styles=L,Mt([o({type:Array})],Ct.prototype,"messages",void 0),Mt([o({type:String})],Ct.prototype,"currentInput",void 0),Mt([o({type:Boolean})],Ct.prototype,"isBotTyping",void 0),Mt([o({type:Boolean})],Ct.prototype,"isQueryRunning",void 0),Mt([o({type:Array})],Ct.prototype,"suggestions",void 0),Mt([o({type:Boolean})],Ct.prototype,"chatStarted",void 0),Mt([o({type:Boolean})],Ct.prototype,"isRTL",void 0),Mt([o({type:String})],Ct.prototype,"size",void 0),Mt([o({type:String})],Ct.prototype,"variant",void 0),Mt([o({type:String})],Ct.prototype,"loadingIndicator",void 0),Mt([o({type:String})],Ct.prototype,"loadingText",void 0),Mt([o({type:Boolean})],Ct.prototype,"disabled",void 0),Mt([o({type:String})],Ct.prototype,"placeholder",void 0),Mt([o({type:Object})],Ct.prototype,"i18n",void 0),Mt([o({type:Boolean})],Ct.prototype,"showSendButton",void 0),Mt([o({type:Boolean})],Ct.prototype,"autoScroll",void 0),Mt([o({type:Boolean})],Ct.prototype,"showThreads",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableThreadCreation",void 0),Mt([o({type:Array})],Ct.prototype,"threads",void 0),Mt([o({type:String,attribute:"active-thread-id"})],Ct.prototype,"activeThreadId",void 0),Mt([o({type:String})],Ct.prototype,"mode",void 0),Mt([o({type:Boolean,reflect:!0})],Ct.prototype,"boxed",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableUrlSync",void 0),Mt([o({type:Boolean})],Ct.prototype,"showMessages",void 0),Mt([o({type:String,attribute:"welcome-message"})],Ct.prototype,"welcomeMessage",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableFileUpload",void 0),Mt([o({type:Array})],Ct.prototype,"uploadedFiles",void 0),Mt([o({type:Array})],Ct.prototype,"actionButtons",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableModuleSelection",void 0),Mt([o({type:Array})],Ct.prototype,"modules",void 0),Mt([o({type:Array})],Ct.prototype,"selectedModules",void 0),Mt([o({type:String})],Ct.prototype,"moduleSelectionLabel",void 0),Mt([o({type:Boolean})],Ct.prototype,"enableArtifacts",void 0),Mt([o({type:Boolean,attribute:"show-audio-button"})],Ct.prototype,"showAudioButton",void 0),Mt([o({type:Function})],Ct.prototype,"onAudioRecorded",void 0),Mt([o({type:Function})],Ct.prototype,"renderArtifactContent",void 0),Mt([o({type:Object})],Ct.prototype,"controller",void 0),Mt([s()],Ct.prototype,"statusText",void 0),Mt([s()],Ct.prototype,"focused",void 0),Mt([s()],Ct.prototype,"isArtifactPanelOpen",void 0),Mt([s()],Ct.prototype,"selectedArtifact",void 0),Mt([s()],Ct.prototype,"isThreadSidebarOpen",void 0),Mt([s()],Ct.prototype,"_editingThreadId",void 0),Mt([s()],Ct.prototype,"isUrlModalOpen",void 0),Mt([s()],Ct.prototype,"urlInput",void 0),Mt([s()],Ct.prototype,"urlModalError",void 0),Mt([s()],Ct.prototype,"isUrlLoading",void 0),Mt([s()],Ct.prototype,"selectedUrlFileName",void 0),Mt([s()],Ct.prototype,"isFilePreviewModalOpen",void 0),Mt([s()],Ct.prototype,"previewFile",void 0),Mt([s()],Ct.prototype,"_isDragging",void 0),Mt([s()],Ct.prototype,"_pendingThreadId",void 0),Mt([s()],Ct.prototype,"_expandedMessageIds",void 0),Mt([o({type:Number,attribute:"message-collapse-threshold"})],Ct.prototype,"messageCollapseThreshold",void 0),Mt([o({type:Boolean,attribute:"inverted-scroll",reflect:!0})],Ct.prototype,"invertedScroll",void 0),Ct=Mt([(t,e)=>(t.addInitializer(b),t),r("nr-chatbot")],Ct);
|
|
2790
2864
|
/**
|
|
2791
2865
|
* @license
|
|
2792
2866
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
@@ -2873,12 +2947,12 @@ var Qt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
|
|
|
2873
2947
|
* @license
|
|
2874
2948
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2875
2949
|
* SPDX-License-Identifier: MIT
|
|
2876
|
-
*/var me=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})},ge=function(t){return this instanceof ge?(this.v=t,this):new ge(t)},ve=function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=i.apply(t,e||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),n[Symbol.asyncIterator]=function(){return this},n;function r(t,e){o[t]&&(n[t]=function(e){return new Promise(function(i,n){s.push([t,e,i,n])>1||a(t,e)})},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=o[t](e)).value instanceof ge?Promise.resolve(i.value.v).then(l,d):c(s[0][2],i)}catch(t){c(s[0][3],t)}var i}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const be={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",toolCall:"tool:call",toolCallEnd:"tool:end"};class
|
|
2950
|
+
*/var me=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})},ge=function(t){return this instanceof ge?(this.v=t,this):new ge(t)},ve=function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=i.apply(t,e||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),n[Symbol.asyncIterator]=function(){return this},n;function r(t,e){o[t]&&(n[t]=function(e){return new Promise(function(i,n){s.push([t,e,i,n])>1||a(t,e)})},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=o[t](e)).value instanceof ge?Promise.resolve(i.value.v).then(l,d):c(s[0][2],i)}catch(t){c(s[0][3],t)}var i}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const be={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",toolCall:"tool:call",toolCallEnd:"tool:end"};class xe{constructor(){this.id="socket",this.name="Socket.io Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.responseResolvers=new Map}connect(t){return me(this,void 0,void 0,function*(){var e,i,n;if(!t.url)throw new Error("Socket URL is required");this.config=Object.assign(Object.assign({},t),{events:Object.assign(Object.assign({},be),t.events),autoReconnect:null===(e=t.autoReconnect)||void 0===e||e,reconnectionAttempts:null!==(i=t.reconnectionAttempts)&&void 0!==i?i:5,responseTimeout:null!==(n=t.responseTimeout)&&void 0!==n?n:3e4});const o=t.namespace?`${t.url}${t.namespace}`:t.url;return this.socket=h(o,{path:t.path||"/socket.io",transports:["websocket","polling"],autoConnect:!0,reconnection:this.config.autoReconnect,reconnectionAttempts:this.config.reconnectionAttempts,extraHeaders:t.headers}),new Promise((t,e)=>{const i=setTimeout(()=>{e(new Error("Socket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(i),this.connected=!0,console.log("[SocketProvider] Connected:",this.socket.id),t()}),this.socket.on("connect_error",t=>{clearTimeout(i),console.error("[SocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[SocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}setupEventListeners(){if(!this.socket||!this.config)return;const t=this.config.events;this.socket.on(t.response,t=>{console.log("[SocketProvider] Response received:",t);const e=this.extractMessageId(t),i=this.responseResolvers.get(e)||this.getLatestResolver();if(i){const n=this.extractMessage(t);i.resolve(n),this.responseResolvers.delete(e)}}),t.stream&&this.socket.on(t.stream,t=>{console.log("[SocketProvider] Stream chunk:",t);const e=this.extractMessageId(t),i=this.responseResolvers.get(e)||this.getLatestResolver();if(i){i.isStreaming=!0;const e=this.extractMessage(t);i.chunks.push(e)}}),t.error&&this.socket.on(t.error,t=>{console.error("[SocketProvider] Error event:",t);const e=this.extractMessageId(t),i=this.responseResolvers.get(e)||this.getLatestResolver();if(i){const n=t.error||t.message||"Unknown error";i.reject(new Error(n)),this.responseResolvers.delete(e)}}),t.toolCall&&this.socket.on(t.toolCall,t=>{var e;const i=t.name||t.toolName||t.function||"unknown";null===(e=this.onToolCall)||void 0===e||e.call(this,i)}),t.toolCallEnd&&this.socket.on(t.toolCallEnd,()=>{var t;null===(t=this.onToolCallEnd)||void 0===t||t.call(this)})}getLatestResolver(){const t=Array.from(this.responseResolvers.keys());return t.length>0?this.responseResolvers.get(t[t.length-1]):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessage(t){var e,i,n;return(null===(e=this.config)||void 0===e?void 0:e.extractMessage)?this.config.extractMessage(t):"string"==typeof t?t:t.message?t.message:t.text?t.text:t.response?t.response:t.content?t.content:(null===(i=t.data)||void 0===i?void 0:i.message)?t.data.message:(null===(n=t.data)||void 0===n?void 0:n.output)?JSON.stringify(t.data.output):JSON.stringify(t)}disconnect(){return me(this,void 0,void 0,function*(){this.socket&&(this.socket.disconnect(),this.socket=null),this.connected=!1,this.responseResolvers.clear(),console.log("[SocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return ve(this,arguments,function*(){if(!this.connected||!this.socket||!this.config)return yield yield ge(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield ge(void 0);const i=`msg_${Date.now()}_${crypto.randomUUID().slice(0,9)}`,n=this.buildPayload(t,e,i);try{const t=new Promise((t,e)=>{this.responseResolvers.set(i,{resolve:t,reject:e,chunks:[],isStreaming:!1}),setTimeout(()=>{const n=this.responseResolvers.get(i);n&&(n.chunks.length>0?t(n.chunks.join("")):e(new Error("Response timeout")),this.responseResolvers.delete(i))},this.config.responseTimeout)});if(console.log("[SocketProvider] Sending message:",this.config.events.send,n),this.socket.emit(this.config.events.send,n),this.config.events.stream){const e=this.responseResolvers.get(i);let n=0;const o=setInterval(()=>{e&&e.chunks.length>n&&(n=e.chunks.length)},50);try{const e=yield ge(t);clearInterval(o),yield yield ge(e)}catch(t){throw clearInterval(o),t}}else{const e=yield ge(t);yield yield ge(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ge(this.formatError("Socket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildPayload(t,e,i){var n,o,s;if(null===(n=this.config)||void 0===n?void 0:n.buildPayload){const n=this.config.buildPayload(t,e);return Object.assign(Object.assign({},n),{messageId:i})}return{messageId:i,message:t,text:t,threadId:null===(o=e.currentThread)||void 0===o?void 0:o.id,modules:e.selectedModules,metadata:e.metadata,files:null===(s=e.uploadedFiles)||void 0===s?void 0:s.map(t=>({id:t.id,name:t.name,type:t.type,url:t.url}))}}emit(t,e){this.socket&&this.connected&&this.socket.emit(t,e)}on(t,e){this.socket&&this.socket.on(t,e)}off(t,e){this.socket&&this.socket.off(t,e)}getSocket(){return this.socket}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[SocketProvider] Error:",t)}}
|
|
2877
2951
|
/**
|
|
2878
2952
|
* @license
|
|
2879
2953
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2880
2954
|
* SPDX-License-Identifier: MIT
|
|
2881
|
-
*/var xe=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})},we=function(t){return this instanceof we?(this.v=t,this):new we(t)},_e=function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=i.apply(t,e||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),n[Symbol.asyncIterator]=function(){return this},n;function r(t,e){o[t]&&(n[t]=function(e){return new Promise(function(i,n){s.push([t,e,i,n])>1||a(t,e)})},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=o[t](e)).value instanceof we?Promise.resolve(i.value.v).then(l,d):c(s[0][2],i)}catch(t){c(s[0][3],t)}var i}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class $e{constructor(){this.id="workflow-socket",this.name="Workflow Socket Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.sessionId=`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`,this.activeExecutions=new Map}connect(t){return xe(this,void 0,void 0,function*(){if(!t.workflowId)throw new Error("Workflow ID is required");this.config=Object.assign({socketUrl:t.socketUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:8000"),socketPath:t.socketPath||"/__nk_socketio/",triggerEndpoint:t.triggerEndpoint||"/api/v1/workflows/{workflowId}/trigger/chat",responseTimeout:t.responseTimeout||6e4},t);const e=`${this.config.socketUrl}/nk/apps/workflows/:workflowId`;return this.socket=h(e,{path:this.config.socketPath,query:{l:JSON.stringify({workflowId:this.config.workflowId})},autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const i=setTimeout(()=>{e(new Error("Socket connection timeout"))},3e4);this.socket.on("connect",()=>{clearTimeout(i),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(i),console.error("[WorkflowSocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[WorkflowSocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}subscribeToWorkflow(t){this.socket&&(this.socket.emit("nk:subscribe:workflow",{workflowId:t}),console.log("[WorkflowSocketProvider] Subscribed to workflow:",t))}subscribeToExecution(t){this.socket&&(this.socket.emit("nk:subscribe:execution",{executionId:t}),console.log("[WorkflowSocketProvider] Subscribed to execution:",t))}setupEventListeners(){this.socket&&(this.socket.onAny((t,...e)=>{console.log("[WorkflowSocketProvider] RAW event:",t,e[0])}),this.socket.on("nk:data",t=>{(null==t?void 0:t.event)&&t.data&&this._handleEvent(t.event,t.data)}),this.socket.on("execution:chat-message",t=>this._handleEvent("execution:chat-message",t)),this.socket.on("execution:started",t=>this._handleEvent("execution:started",t)),this.socket.on("execution:completed",t=>this._handleEvent("execution:completed",t)),this.socket.on("execution:failed",t=>this._handleEvent("execution:failed",t)),this.socket.on("execution:node-started",t=>this._handleEvent("execution:node-started",t)),this.socket.on("execution:node-completed",t=>this._handleEvent("execution:node-completed",t)))}_handleEvent(t,e){var i,n,o,s,r;switch(t){case"execution:chat-message":{const t=e.executionId,o=e.message;if(console.log("[WorkflowSocketProvider] Chat message received:",t,o),!t||!o)return;const s=this.activeExecutions.get(t);if(!s)return void(null===(n=null===(i=this.config)||void 0===i?void 0:i.onMessage)||void 0===n||n.call(i,o));s.completed||s.messages.push(o);break}case"execution:started":console.log("[WorkflowSocketProvider] Execution started (event):",e.executionId);break;case"execution:completed":{const t=e.executionId;if(console.log("[WorkflowSocketProvider] Execution completed:",t),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0;let n="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)n=this.config.extractResponse(e);else if(i.messages.length>0)n=i.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;n=t.response||t.message||t.result||JSON.stringify(t)}catch(t){n=e.outputData}i.resolve(n||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,i=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,i),!t)return;const n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0,n.reject(new Error(i)),this.activeExecutions.delete(t);break}case"execution:node-started":console.log("[WorkflowSocketProvider] Node started:",e.nodeName),e.nodeName&&(null===(s=this.onNodeStarted)||void 0===s||s.call(this,e.nodeName));break;case"execution:node-completed":console.log("[WorkflowSocketProvider] Node completed:",e.nodeName),e.nodeName&&(null===(r=this.onNodeCompleted)||void 0===r||r.call(this,e.nodeName))}}disconnect(){return xe(this,void 0,void 0,function*(){var t;this.socket&&((null===(t=this.config)||void 0===t?void 0:t.workflowId)&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.socket.disconnect(),this.socket=null),this.connected=!1,this.activeExecutions.clear(),console.log("[WorkflowSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return _e(this,arguments,function*(){var i,n;if(!this.connected||!this.socket||!this.config)return yield yield we(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield we(void 0);try{const o=this.buildInput(t,e),s=this.config.triggerEndpoint.replace("{workflowId}",this.config.workflowId),r=`${this.config.socketUrl}${s}`;console.log("[WorkflowSocketProvider] Triggering workflow:",r,o);const a=yield we(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield we(a.text().catch(()=>a.statusText));return yield yield we(this.formatError(`${a.status} ${a.statusText}`,t)),yield we(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(i=yield we(a.json().catch(()=>({}))))||void 0===i?void 0:i.executionId);if(!l)return yield yield we(this.formatError("Execution Error","No execution ID received from server")),yield we(void 0);console.log("[WorkflowSocketProvider] Execution started:",l),(null===(n=this.config)||void 0===n?void 0:n.onExecutionStart)&&this.config.onExecutionStart(l,this.config.workflowId),this.subscribeToExecution(l);const d=new Promise((t,e)=>{this.activeExecutions.set(l,{messages:[],resolve:t,reject:e,completed:!1}),setTimeout(()=>{const i=this.activeExecutions.get(l);i&&!i.completed&&(i.completed=!0,i.messages.length>0?t(i.messages.join("\n\n")):e(new Error("Execution timeout")),this.activeExecutions.delete(l))},this.config.responseTimeout)}),c=this.activeExecutions.get(l);let h=0;const u=setInterval(()=>{c.messages.length>h&&(h=c.messages.length)},100);try{for(;!c.completed;){if(c.messages.length>0){const t=c.messages.join("\n\n");yield yield we(t)}yield we(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield we(d);yield yield we(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield we(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var i,n,o;if(null===(i=this.config)||void 0===i?void 0:i.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(n=e.currentThread)||void 0===n?void 0:n.id)||this.sessionId,r={message:t,threadId:s,modules:e.selectedModules,metadata:e.metadata,files:(null===(o=e.uploadedFiles)||void 0===o?void 0:o.map(t=>{var e;return{id:t.id,name:t.name,type:t.type,mimeType:t.mimeType,url:t.url,base64:null===(e=t.metadata)||void 0===e?void 0:e.base64}}))||[]};return console.log("[WorkflowSocketProvider] buildInput threadId:",s,"files count:",r.files.length),r}setWorkflowId(t){this.config&&(this.socket&&this.config.workflowId&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.config.workflowId=t,this.socket&&this.connected&&this.subscribeToWorkflow(t))}getSocket(){return this.socket}uploadFile(t){return xe(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,i=URL.createObjectURL(t),n=yield this.fileToBase64(t),o=t.type||"application/octet-stream",s=this.determineFileType(o);return console.log(`[WorkflowSocketProvider] File prepared: ${t.name} (${t.size} bytes)`),{id:e,name:t.name,size:t.size,type:s,mimeType:o,url:i,previewUrl:s===Q.Image?i:void 0,uploadProgress:100,metadata:{provider:"workflow-socket",uploadedAt:(new Date).toISOString(),base64:n}}})}fileToBase64(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{const t=n.result,i=t.split(",")[1]||t;e(i)},n.onerror=i,n.readAsDataURL(t)})}determineFileType(t){return t.startsWith("image/")?Q.Image:t.startsWith("video/")?Q.Video:t.startsWith("audio/")?Q.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?Q.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?Q.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?Q.Code:Q.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2955
|
+
*/var ye=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})},we=function(t){return this instanceof we?(this.v=t,this):new we(t)},_e=function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=i.apply(t,e||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),n[Symbol.asyncIterator]=function(){return this},n;function r(t,e){o[t]&&(n[t]=function(e){return new Promise(function(i,n){s.push([t,e,i,n])>1||a(t,e)})},e&&(n[t]=e(n[t])))}function a(t,e){try{(i=o[t](e)).value instanceof we?Promise.resolve(i.value.v).then(l,d):c(s[0][2],i)}catch(t){c(s[0][3],t)}var i}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class $e{constructor(){this.id="workflow-socket",this.name="Workflow Socket Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.sessionId=`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`,this.activeExecutions=new Map}connect(t){return ye(this,void 0,void 0,function*(){if(!t.workflowId)throw new Error("Workflow ID is required");this.config=Object.assign({socketUrl:t.socketUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:8000"),socketPath:t.socketPath||"/__nk_socketio/",triggerEndpoint:t.triggerEndpoint||"/api/v1/workflows/{workflowId}/trigger/chat",responseTimeout:t.responseTimeout||6e4},t);const e=`${this.config.socketUrl}/nk/apps/workflows/:workflowId`;return this.socket=h(e,{path:this.config.socketPath,query:{l:JSON.stringify({workflowId:this.config.workflowId})},autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const i=setTimeout(()=>{e(new Error("Socket connection timeout"))},3e4);this.socket.on("connect",()=>{clearTimeout(i),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(i),console.error("[WorkflowSocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[WorkflowSocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}subscribeToWorkflow(t){this.socket&&(this.socket.emit("nk:subscribe:workflow",{workflowId:t}),console.log("[WorkflowSocketProvider] Subscribed to workflow:",t))}subscribeToExecution(t){this.socket&&(this.socket.emit("nk:subscribe:execution",{executionId:t}),console.log("[WorkflowSocketProvider] Subscribed to execution:",t))}setupEventListeners(){this.socket&&(this.socket.onAny((t,...e)=>{console.log("[WorkflowSocketProvider] RAW event:",t,e[0])}),this.socket.on("nk:data",t=>{(null==t?void 0:t.event)&&t.data&&this._handleEvent(t.event,t.data)}),this.socket.on("execution:chat-message",t=>this._handleEvent("execution:chat-message",t)),this.socket.on("execution:started",t=>this._handleEvent("execution:started",t)),this.socket.on("execution:completed",t=>this._handleEvent("execution:completed",t)),this.socket.on("execution:failed",t=>this._handleEvent("execution:failed",t)),this.socket.on("execution:node-started",t=>this._handleEvent("execution:node-started",t)),this.socket.on("execution:node-completed",t=>this._handleEvent("execution:node-completed",t)))}_handleEvent(t,e){var i,n,o,s,r;switch(t){case"execution:chat-message":{const t=e.executionId,o=e.message;if(console.log("[WorkflowSocketProvider] Chat message received:",t,o),!t||!o)return;const s=this.activeExecutions.get(t);if(!s)return void(null===(n=null===(i=this.config)||void 0===i?void 0:i.onMessage)||void 0===n||n.call(i,o));s.completed||s.messages.push(o);break}case"execution:started":console.log("[WorkflowSocketProvider] Execution started (event):",e.executionId);break;case"execution:completed":{const t=e.executionId;if(console.log("[WorkflowSocketProvider] Execution completed:",t),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0;let n="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)n=this.config.extractResponse(e);else if(i.messages.length>0)n=i.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;n=t.response||t.message||t.result||JSON.stringify(t)}catch(t){n=e.outputData}i.resolve(n||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,i=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,i),!t)return;const n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0,n.reject(new Error(i)),this.activeExecutions.delete(t);break}case"execution:node-started":console.log("[WorkflowSocketProvider] Node started:",e.nodeName),e.nodeName&&(null===(s=this.onNodeStarted)||void 0===s||s.call(this,e.nodeName));break;case"execution:node-completed":console.log("[WorkflowSocketProvider] Node completed:",e.nodeName),e.nodeName&&(null===(r=this.onNodeCompleted)||void 0===r||r.call(this,e.nodeName))}}disconnect(){return ye(this,void 0,void 0,function*(){var t;this.socket&&((null===(t=this.config)||void 0===t?void 0:t.workflowId)&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.socket.disconnect(),this.socket=null),this.connected=!1,this.activeExecutions.clear(),console.log("[WorkflowSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return _e(this,arguments,function*(){var i,n;if(!this.connected||!this.socket||!this.config)return yield yield we(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield we(void 0);try{const o=this.buildInput(t,e),s=this.config.triggerEndpoint.replace("{workflowId}",this.config.workflowId),r=`${this.config.socketUrl}${s}`;console.log("[WorkflowSocketProvider] Triggering workflow:",r,o);const a=yield we(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield we(a.text().catch(()=>a.statusText));return yield yield we(this.formatError(`${a.status} ${a.statusText}`,t)),yield we(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(i=yield we(a.json().catch(()=>({}))))||void 0===i?void 0:i.executionId);if(!l)return yield yield we(this.formatError("Execution Error","No execution ID received from server")),yield we(void 0);console.log("[WorkflowSocketProvider] Execution started:",l),(null===(n=this.config)||void 0===n?void 0:n.onExecutionStart)&&this.config.onExecutionStart(l,this.config.workflowId),this.subscribeToExecution(l);const d=new Promise((t,e)=>{this.activeExecutions.set(l,{messages:[],resolve:t,reject:e,completed:!1}),setTimeout(()=>{const i=this.activeExecutions.get(l);i&&!i.completed&&(i.completed=!0,i.messages.length>0?t(i.messages.join("\n\n")):e(new Error("Execution timeout")),this.activeExecutions.delete(l))},this.config.responseTimeout)}),c=this.activeExecutions.get(l);let h=0;const u=setInterval(()=>{c.messages.length>h&&(h=c.messages.length)},100);try{for(;!c.completed;){if(c.messages.length>0){const t=c.messages.join("\n\n");yield yield we(t)}yield we(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield we(d);yield yield we(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield we(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var i,n,o;if(null===(i=this.config)||void 0===i?void 0:i.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(n=e.currentThread)||void 0===n?void 0:n.id)||this.sessionId,r={message:t,threadId:s,modules:e.selectedModules,metadata:e.metadata,files:(null===(o=e.uploadedFiles)||void 0===o?void 0:o.map(t=>{var e;return{id:t.id,name:t.name,type:t.type,mimeType:t.mimeType,url:t.url,base64:null===(e=t.metadata)||void 0===e?void 0:e.base64}}))||[]};return console.log("[WorkflowSocketProvider] buildInput threadId:",s,"files count:",r.files.length),r}setWorkflowId(t){this.config&&(this.socket&&this.config.workflowId&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.config.workflowId=t,this.socket&&this.connected&&this.subscribeToWorkflow(t))}getSocket(){return this.socket}uploadFile(t){return ye(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,i=URL.createObjectURL(t),n=yield this.fileToBase64(t),o=t.type||"application/octet-stream",s=this.determineFileType(o);return console.log(`[WorkflowSocketProvider] File prepared: ${t.name} (${t.size} bytes)`),{id:e,name:t.name,size:t.size,type:s,mimeType:o,url:i,previewUrl:s===Q.Image?i:void 0,uploadProgress:100,metadata:{provider:"workflow-socket",uploadedAt:(new Date).toISOString(),base64:n}}})}fileToBase64(t){return new Promise((e,i)=>{const n=new FileReader;n.onload=()=>{const t=n.result,i=t.split(",")[1]||t;e(i)},n.onerror=i,n.readAsDataURL(t)})}determineFileType(t){return t.startsWith("image/")?Q.Image:t.startsWith("video/")?Q.Video:t.startsWith("audio/")?Q.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?Q.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?Q.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?Q.Code:Q.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2882
2956
|
/**
|
|
2883
2957
|
* @license
|
|
2884
2958
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
@@ -2956,4 +3030,4 @@ var Qt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
|
|
|
2956
3030
|
* Pipeline:
|
|
2957
3031
|
* input blob → AudioContext.decodeAudioData → BufferSource → MediaStreamDestination
|
|
2958
3032
|
* → MediaRecorder(ogg/opus, 32 kbps) → output blob
|
|
2959
|
-
*/var Ze=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})};const ti="audio/ogg;codecs=opus";function ei(){try{return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported(ti)}catch(t){return!1}}var ii=Object.freeze({__proto__:null,canEncodeOgg:ei,compressToOpus:function(t,e){return Ze(this,void 0,void 0,function*(){if(!ei()){const i=e.includes("mp4")?"mp4":e.includes("aac")?"aac":"webm";return{blob:t,mimeType:e,ext:i}}const i=yield t.arrayBuffer(),n=new AudioContext;let o;try{o=yield n.decodeAudioData(i)}finally{n.close().catch(()=>{})}const s=new AudioContext({sampleRate:o.sampleRate}),r=s.createMediaStreamDestination(),a=new MediaRecorder(r.stream,{mimeType:ti,audioBitsPerSecond:32e3}),l=[];a.ondataavailable=t=>{t.data.size>0&&l.push(t.data)};const d=new Promise((t,e)=>{a.onstop=()=>t(),a.onerror=t=>{var i;return e(null!==(i=t.error)&&void 0!==i?i:new Error("MediaRecorder error"))}});a.start(100);const c=s.createBufferSource();return c.buffer=o,c.connect(r),c.onended=()=>{setTimeout(()=>{"recording"===a.state&&a.stop()},120)},c.start(0),yield d,s.close().catch(()=>{}),{blob:new Blob(l,{type:ti}),mimeType:ti,ext:"ogg"}})}});export{ze as AnalyticsPlugin,De as ArtifactPlugin,Oe as ChatPluginBase,X as ChatbotActionType,Xt as ChatbotCoreController,Q as ChatbotFileType,V as ChatbotLoadingType,Y as ChatbotMessageState,Xe as ChatbotScrollController,q as ChatbotSender,G as ChatbotSize,K as ChatbotVariant,re as CustomAPIProvider,ot as DEFAULT_ALLOWED_FILE_TYPES,nt as DEFAULT_MAX_FILES,it as DEFAULT_MAX_FILE_SIZE,et as DEFAULT_MAX_MESSAGES,tt as DEFAULT_TYPING_DELAY,Z as EMPTY_STRING,zt as EventBus,st as FILE_TYPE_MAPPINGS,Ft as FileHandler,Ae as FlightCardPlugin,Je as FlowDiagramPlugin,Qe as IndexedDBStorage,Be as JsonGraphRendererPlugin,Ye as LocalStorageAdapter,je as MarkdownPlugin,Ke as MemoryStorage,jt as MessageHandler,pe as MockProvider,fe as MockProviders,Dt as ModuleHandler,Te as NativeWebSocketProvider,Ct as NrChatbotElement,ie as OpenAIProvider,Ce as PersistencePlugin,Gt as PluginService,Le as PrintJobCardPlugin,Ut as ProviderService,Ve as SelectionCardPlugin,
|
|
3033
|
+
*/var Ze=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})};const ti="audio/ogg;codecs=opus";function ei(){try{return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported(ti)}catch(t){return!1}}var ii=Object.freeze({__proto__:null,canEncodeOgg:ei,compressToOpus:function(t,e){return Ze(this,void 0,void 0,function*(){if(!ei()){const i=e.includes("mp4")?"mp4":e.includes("aac")?"aac":"webm";return{blob:t,mimeType:e,ext:i}}const i=yield t.arrayBuffer(),n=new AudioContext;let o;try{o=yield n.decodeAudioData(i)}finally{n.close().catch(()=>{})}const s=new AudioContext({sampleRate:o.sampleRate}),r=s.createMediaStreamDestination(),a=new MediaRecorder(r.stream,{mimeType:ti,audioBitsPerSecond:32e3}),l=[];a.ondataavailable=t=>{t.data.size>0&&l.push(t.data)};const d=new Promise((t,e)=>{a.onstop=()=>t(),a.onerror=t=>{var i;return e(null!==(i=t.error)&&void 0!==i?i:new Error("MediaRecorder error"))}});a.start(100);const c=s.createBufferSource();return c.buffer=o,c.connect(r),c.onended=()=>{setTimeout(()=>{"recording"===a.state&&a.stop()},120)},c.start(0),yield d,s.close().catch(()=>{}),{blob:new Blob(l,{type:ti}),mimeType:ti,ext:"ogg"}})}});export{ze as AnalyticsPlugin,De as ArtifactPlugin,Oe as ChatPluginBase,X as ChatbotActionType,Xt as ChatbotCoreController,Q as ChatbotFileType,V as ChatbotLoadingType,Y as ChatbotMessageState,Xe as ChatbotScrollController,q as ChatbotSender,G as ChatbotSize,K as ChatbotVariant,re as CustomAPIProvider,ot as DEFAULT_ALLOWED_FILE_TYPES,nt as DEFAULT_MAX_FILES,it as DEFAULT_MAX_FILE_SIZE,et as DEFAULT_MAX_MESSAGES,tt as DEFAULT_TYPING_DELAY,Z as EMPTY_STRING,zt as EventBus,st as FILE_TYPE_MAPPINGS,Ft as FileHandler,Ae as FlightCardPlugin,Je as FlowDiagramPlugin,Qe as IndexedDBStorage,Be as JsonGraphRendererPlugin,Ye as LocalStorageAdapter,je as MarkdownPlugin,Ke as MemoryStorage,jt as MessageHandler,pe as MockProvider,fe as MockProviders,Dt as ModuleHandler,Te as NativeWebSocketProvider,Ct as NrChatbotElement,ie as OpenAIProvider,Ce as PersistencePlugin,Gt as PluginService,Le as PrintJobCardPlugin,Ut as ProviderService,Ve as SelectionCardPlugin,xe as SocketProvider,It as StateHandler,qt as StorageService,Bt as SuggestionHandler,At as ThreadHandler,Ot as ValidationError,Ht as ValidationService,$e as WorkflowSocketProvider};
|
|
Binary file
|
|
@@ -172,6 +172,19 @@ export declare class NrChatbotElement extends NrChatbotElement_base {
|
|
|
172
172
|
private teardownUrlSync;
|
|
173
173
|
private handleHashChange;
|
|
174
174
|
private _pendingThreadId?;
|
|
175
|
+
private _expandedMessageIds;
|
|
176
|
+
/**
|
|
177
|
+
* Character count above which a user message is collapsed with a "Show more"
|
|
178
|
+
* toggle and a bubble-colored gradient. Set to 0 to disable. Default 600.
|
|
179
|
+
*/
|
|
180
|
+
messageCollapseThreshold: number;
|
|
181
|
+
/**
|
|
182
|
+
* Anchor the messages column to the bottom. New messages stay at the bottom
|
|
183
|
+
* automatically (browser-native scroll anchoring via flex-direction column-reverse).
|
|
184
|
+
* When the user scrolls up to read history, new arriving messages do not pull
|
|
185
|
+
* them back down. Implies that auto-scroll JS is skipped.
|
|
186
|
+
*/
|
|
187
|
+
invertedScroll: boolean;
|
|
175
188
|
private syncActiveThreadToController;
|
|
176
189
|
private handleControllerStateChange;
|
|
177
190
|
private handleControllerMessageSent;
|
|
@@ -81,6 +81,8 @@ const DEFAULT_I18N = {
|
|
|
81
81
|
startConversationLabel: msg('Start a conversation'),
|
|
82
82
|
suggestionPrefix: msg('Select suggestion: '),
|
|
83
83
|
loadingConversationLabel: msg('Loading conversation…'),
|
|
84
|
+
showMoreLabel: msg('Show more'),
|
|
85
|
+
showLessLabel: msg('Show less'),
|
|
84
86
|
},
|
|
85
87
|
urlModal: {
|
|
86
88
|
addUrlTitle: msg('Add URL'),
|
|
@@ -214,6 +216,19 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
214
216
|
this._audioMode = 'message';
|
|
215
217
|
// Artifact panel resize state
|
|
216
218
|
this._artifactResizeBound = false;
|
|
219
|
+
this._expandedMessageIds = new Set();
|
|
220
|
+
/**
|
|
221
|
+
* Character count above which a user message is collapsed with a "Show more"
|
|
222
|
+
* toggle and a bubble-colored gradient. Set to 0 to disable. Default 600.
|
|
223
|
+
*/
|
|
224
|
+
this.messageCollapseThreshold = 600;
|
|
225
|
+
/**
|
|
226
|
+
* Anchor the messages column to the bottom. New messages stay at the bottom
|
|
227
|
+
* automatically (browser-native scroll anchoring via flex-direction column-reverse).
|
|
228
|
+
* When the user scrolls up to read history, new arriving messages do not pull
|
|
229
|
+
* them back down. Implies that auto-scroll JS is skipped.
|
|
230
|
+
*/
|
|
231
|
+
this.invertedScroll = false;
|
|
217
232
|
this.toggleThreadSidebar = () => {
|
|
218
233
|
this.isThreadSidebarOpen = !this.isThreadSidebarOpen;
|
|
219
234
|
};
|
|
@@ -247,7 +262,7 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
247
262
|
this.setupUrlSync();
|
|
248
263
|
}
|
|
249
264
|
firstUpdated() {
|
|
250
|
-
var _a, _b, _c, _d;
|
|
265
|
+
var _a, _b, _c, _d, _e;
|
|
251
266
|
// Event delegation for artifact card clicks (injected via unsafeHTML)
|
|
252
267
|
(_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.addEventListener('click', (e) => {
|
|
253
268
|
var _a, _b;
|
|
@@ -286,8 +301,24 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
286
301
|
}
|
|
287
302
|
}
|
|
288
303
|
});
|
|
304
|
+
// Show more / Show less on collapsed user messages
|
|
305
|
+
(_d = this.shadowRoot) === null || _d === void 0 ? void 0 : _d.addEventListener('click', (e) => {
|
|
306
|
+
var _a, _b;
|
|
307
|
+
const toggle = (_b = (_a = e.target).closest) === null || _b === void 0 ? void 0 : _b.call(_a, '[data-message-toggle]');
|
|
308
|
+
if (toggle) {
|
|
309
|
+
const id = toggle.dataset.messageToggle;
|
|
310
|
+
if (id) {
|
|
311
|
+
const next = new Set(this._expandedMessageIds);
|
|
312
|
+
if (next.has(id))
|
|
313
|
+
next.delete(id);
|
|
314
|
+
else
|
|
315
|
+
next.add(id);
|
|
316
|
+
this._expandedMessageIds = next;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
});
|
|
289
320
|
// Keyboard support for artifact cards and selection cards
|
|
290
|
-
(
|
|
321
|
+
(_e = this.shadowRoot) === null || _e === void 0 ? void 0 : _e.addEventListener('keydown', (e) => {
|
|
291
322
|
var _a, _b, _c, _d;
|
|
292
323
|
const ke = e;
|
|
293
324
|
if (ke.key !== 'Enter' && ke.key !== ' ')
|
|
@@ -371,8 +402,10 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
371
402
|
}
|
|
372
403
|
}
|
|
373
404
|
}
|
|
374
|
-
// Auto-scroll when messages are added or updated
|
|
375
|
-
|
|
405
|
+
// Auto-scroll when messages are added or updated.
|
|
406
|
+
// Skipped in inverted-scroll mode: the column-reverse layout anchors the
|
|
407
|
+
// newest message at the bottom natively and JS scrolling fights that.
|
|
408
|
+
if (changedProperties.has('messages') && this.autoScroll && !this.invertedScroll && this.messages.length > 0) {
|
|
376
409
|
this.scrollToLatestMessage();
|
|
377
410
|
}
|
|
378
411
|
// Attach/detach artifact panel resize handle
|
|
@@ -571,6 +604,7 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
571
604
|
showMessages: this.showMessages,
|
|
572
605
|
welcomeMessage: this.welcomeMessage,
|
|
573
606
|
isPendingThread: !!this._pendingThreadId,
|
|
607
|
+
invertedScroll: this.invertedScroll,
|
|
574
608
|
messages: this.messages,
|
|
575
609
|
isTyping: this.isBotTyping,
|
|
576
610
|
loadingIndicator: this.loadingIndicator,
|
|
@@ -633,7 +667,9 @@ let NrChatbotElement = class NrChatbotElement extends NuralyUIBaseMixin(LitEleme
|
|
|
633
667
|
onRetryKeydown: () => { },
|
|
634
668
|
onCopy: this.handleCopyMessage.bind(this),
|
|
635
669
|
onCopyKeydown: () => { },
|
|
636
|
-
onFileClick: this.handleFilePreview.bind(this)
|
|
670
|
+
onFileClick: this.handleFilePreview.bind(this),
|
|
671
|
+
collapseThreshold: this.messageCollapseThreshold,
|
|
672
|
+
isExpanded: (id) => this._expandedMessageIds.has(id),
|
|
637
673
|
},
|
|
638
674
|
suggestion: {
|
|
639
675
|
onClick: this.handleSuggestionClick.bind(this),
|
|
@@ -1357,6 +1393,15 @@ __decorate([
|
|
|
1357
1393
|
__decorate([
|
|
1358
1394
|
state()
|
|
1359
1395
|
], NrChatbotElement.prototype, "_pendingThreadId", void 0);
|
|
1396
|
+
__decorate([
|
|
1397
|
+
state()
|
|
1398
|
+
], NrChatbotElement.prototype, "_expandedMessageIds", void 0);
|
|
1399
|
+
__decorate([
|
|
1400
|
+
property({ type: Number, attribute: 'message-collapse-threshold' })
|
|
1401
|
+
], NrChatbotElement.prototype, "messageCollapseThreshold", void 0);
|
|
1402
|
+
__decorate([
|
|
1403
|
+
property({ type: Boolean, attribute: 'inverted-scroll', reflect: true })
|
|
1404
|
+
], NrChatbotElement.prototype, "invertedScroll", void 0);
|
|
1360
1405
|
NrChatbotElement = __decorate([
|
|
1361
1406
|
localized(),
|
|
1362
1407
|
customElement('nr-chatbot')
|