@nuraly/lumenui 0.6.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/README.md +22 -0
- package/dist/cdn.js +1 -1
- package/dist/nuralyui.bundle.js +167 -104
- package/dist/nuralyui.bundle.js.gz +0 -0
- package/dist/src/components/canvas/bundle.js +138 -64
- package/dist/src/components/canvas/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/bundle.js +161 -87
- package/dist/src/components/chatbot/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/chatbot.component.d.ts +26 -2
- package/dist/src/components/chatbot/chatbot.component.js +131 -15
- package/dist/src/components/chatbot/chatbot.style.js +84 -42
- package/dist/src/components/chatbot/chatbot.types.d.ts +3 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.d.ts +6 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.js +6 -4
- package/dist/src/components/chatbot/templates/message.template.d.ts +5 -8
- package/dist/src/components/chatbot/templates/message.template.js +64 -19
- package/package.json +1 -1
- package/packages/themes/dist/default.css +12 -0
|
@@ -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,
|
|
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%;
|
|
@@ -60,10 +60,10 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
60
60
|
display: flex;
|
|
61
61
|
width: 100%;
|
|
62
62
|
height: 100%;
|
|
63
|
-
background-color: #ffffff;
|
|
64
63
|
border-radius: 8px;
|
|
65
64
|
position: relative;
|
|
66
65
|
border: 1px solid #e0e0e0;
|
|
66
|
+
box-sizing: border-box;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
.chatbot-container {
|
|
@@ -88,13 +88,24 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
88
88
|
min-width: 0;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
.chatbot-boxed-area {
|
|
92
|
+
display: flex;
|
|
93
|
+
flex-direction: column;
|
|
94
|
+
flex: 1;
|
|
95
|
+
min-height: 0;
|
|
96
|
+
min-width: 0;
|
|
97
|
+
width: 100%;
|
|
98
|
+
}
|
|
99
|
+
|
|
91
100
|
.chatbot-header {
|
|
92
101
|
display: flex;
|
|
93
102
|
align-items: center;
|
|
94
103
|
justify-content: space-between;
|
|
95
104
|
gap: 0.5rem;
|
|
96
105
|
padding: 0.5rem;
|
|
97
|
-
|
|
106
|
+
min-height: 43px;
|
|
107
|
+
box-sizing: border-box;
|
|
108
|
+
border-bottom: 1px solid var(--nuraly-color-divider, rgb(224, 224, 224));
|
|
98
109
|
}
|
|
99
110
|
|
|
100
111
|
.chatbot-content {
|
|
@@ -106,7 +117,6 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
106
117
|
}
|
|
107
118
|
|
|
108
119
|
:host([boxed]) .chat-container {
|
|
109
|
-
background-color: #ffffff;
|
|
110
120
|
border: none;
|
|
111
121
|
border-radius: 0;
|
|
112
122
|
}
|
|
@@ -117,22 +127,15 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
117
127
|
|
|
118
128
|
:host([boxed]) .chatbot-main {
|
|
119
129
|
width: 100%;
|
|
120
|
-
max-width: 768px;
|
|
121
|
-
margin: 0 auto;
|
|
122
|
-
background-color: #ffffff;
|
|
123
130
|
border: none;
|
|
124
131
|
border-radius: 0;
|
|
125
132
|
box-shadow: none;
|
|
126
133
|
height: 100%;
|
|
127
134
|
}
|
|
128
135
|
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
.chat-container--boxed.chat-container--with-threads .chatbot-main {
|
|
135
|
-
background-color: #ffffff;
|
|
136
|
+
:host([boxed]) .chatbot-boxed-area {
|
|
137
|
+
max-width: 768px;
|
|
138
|
+
margin: 0 auto;
|
|
136
139
|
}
|
|
137
140
|
|
|
138
141
|
.chat-container--boxed.chat-container--with-threads .chat-box {
|
|
@@ -148,9 +151,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
148
151
|
}
|
|
149
152
|
|
|
150
153
|
:host([boxed]) .chatbot-header {
|
|
151
|
-
/* Keep header at the top */
|
|
152
154
|
flex: 0 0 auto;
|
|
153
|
-
border-bottom: none;
|
|
154
155
|
}
|
|
155
156
|
|
|
156
157
|
:host([boxed]) .chatbot-content:has(.empty-state) {
|
|
@@ -164,24 +165,15 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
164
165
|
min-height: 0;
|
|
165
166
|
}
|
|
166
167
|
|
|
167
|
-
:host([boxed]) .chatbot-main:has(.empty-state) {
|
|
168
|
-
/* Make main container relative for absolute positioning */
|
|
169
|
-
position: relative;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
168
|
:host([boxed]) .empty-state {
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
transform: translate(-50%, calc(-50% - 80px));
|
|
169
|
+
display: flex;
|
|
170
|
+
align-items: center;
|
|
171
|
+
justify-content: center;
|
|
172
|
+
flex-direction: column;
|
|
178
173
|
width: 100%;
|
|
174
|
+
height: 100%;
|
|
179
175
|
max-width: 768px;
|
|
180
|
-
height: auto;
|
|
181
176
|
padding: 0;
|
|
182
|
-
display: flex;
|
|
183
|
-
flex-direction: column;
|
|
184
|
-
align-items: center;
|
|
185
177
|
gap: 1.5rem;
|
|
186
178
|
}
|
|
187
179
|
|
|
@@ -190,13 +182,9 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
190
182
|
}
|
|
191
183
|
|
|
192
184
|
:host([boxed]) .chatbot-content:has(.empty-state) + .input-box {
|
|
193
|
-
/* Position input-box in the middle with empty state - moved up */
|
|
194
|
-
position: absolute;
|
|
195
|
-
top: 50%;
|
|
196
|
-
left: 50%;
|
|
197
|
-
transform: translate(-50%, calc(-50% + 40px));
|
|
198
185
|
width: 100%;
|
|
199
186
|
max-width: 768px;
|
|
187
|
+
margin: 0 auto;
|
|
200
188
|
}
|
|
201
189
|
|
|
202
190
|
:host([boxed]) .suggestion-container {
|
|
@@ -206,7 +194,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
206
194
|
:host([boxed]) .messages {
|
|
207
195
|
box-shadow: none;
|
|
208
196
|
margin-bottom: 0;
|
|
209
|
-
background-color:
|
|
197
|
+
background-color: var(--chatbot-messages-bg, transparent);
|
|
210
198
|
align-items: stretch;
|
|
211
199
|
width: 98%;
|
|
212
200
|
padding: 8px 1.5rem;
|
|
@@ -250,7 +238,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
250
238
|
align-items: center;
|
|
251
239
|
justify-content: space-between;
|
|
252
240
|
padding: 0.75rem;
|
|
253
|
-
border-bottom: 1px solid
|
|
241
|
+
border-bottom: 1px solid var(--nuraly-color-divider, rgb(224, 224, 224));
|
|
254
242
|
}
|
|
255
243
|
|
|
256
244
|
.thread-sidebar__header h3 {
|
|
@@ -461,17 +449,23 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
461
449
|
|
|
462
450
|
.messages {
|
|
463
451
|
flex: 1;
|
|
452
|
+
min-height: 0;
|
|
464
453
|
overflow-y: auto;
|
|
465
454
|
overflow-x: hidden;
|
|
466
455
|
display: flex;
|
|
467
456
|
flex-direction: column;
|
|
468
457
|
gap: 0;
|
|
469
|
-
background-color:
|
|
458
|
+
background-color: var(--chatbot-messages-bg, transparent);
|
|
470
459
|
padding: 8px 1rem;
|
|
471
460
|
box-sizing: border-box;
|
|
472
461
|
justify-content: flex-start; /* Always align messages to top */
|
|
473
462
|
}
|
|
474
463
|
|
|
464
|
+
.messages--inverted {
|
|
465
|
+
flex-direction: column-reverse;
|
|
466
|
+
justify-content: flex-start;
|
|
467
|
+
}
|
|
468
|
+
|
|
475
469
|
.empty-state {
|
|
476
470
|
display: flex;
|
|
477
471
|
flex-direction: column;
|
|
@@ -605,16 +599,64 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
605
599
|
}
|
|
606
600
|
|
|
607
601
|
.message.user .message__content {
|
|
608
|
-
background-color:
|
|
609
|
-
color:
|
|
602
|
+
background-color: var(--nuraly-color-user-bubble-bg, rgb(124, 58, 237));
|
|
603
|
+
color: var(--nuraly-color-user-bubble-fg, rgb(255, 255, 255));
|
|
610
604
|
border-radius: var(--chatbot-radius, 8px);
|
|
611
605
|
border: 0 solid transparent;
|
|
612
606
|
box-shadow: none;
|
|
613
607
|
}
|
|
614
608
|
|
|
615
|
-
.
|
|
616
|
-
|
|
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;
|
|
617
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
|
+
|
|
657
|
+
.message.bot .message__content {
|
|
658
|
+
background-color: var(--nuraly-color-bot-bubble-bg, transparent);
|
|
659
|
+
color: var(--nuraly-color-bot-bubble-fg, inherit);
|
|
618
660
|
border-radius: 0;
|
|
619
661
|
border: 0 solid transparent;
|
|
620
662
|
box-shadow: none;
|
|
@@ -1659,10 +1701,10 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1659
1701
|
.artifact-panel {
|
|
1660
1702
|
width: 400px;
|
|
1661
1703
|
min-width: 300px;
|
|
1704
|
+
min-height: 0;
|
|
1662
1705
|
flex-shrink: 0;
|
|
1663
1706
|
display: flex;
|
|
1664
1707
|
flex-direction: row;
|
|
1665
|
-
background-color: #ffffff;
|
|
1666
1708
|
overflow: hidden;
|
|
1667
1709
|
position: relative;
|
|
1668
1710
|
}
|
|
@@ -1985,20 +2027,34 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1985
2027
|
* @license
|
|
1986
2028
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1987
2029
|
* SPDX-License-Identifier: MIT
|
|
1988
|
-
*/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
|
|
1989
|
-
<div
|
|
1990
|
-
class="message ${a(g)}"
|
|
1991
|
-
part="message"
|
|
1992
|
-
data-sender="${t.sender}"
|
|
1993
|
-
data-id="${t.id}"
|
|
1994
|
-
>
|
|
1995
|
-
<div class="message__content" part="message-content">
|
|
1996
|
-
${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`
|
|
1997
2031
|
<div class="message__error-container" part="message-error">
|
|
1998
2032
|
${t?i`<div class="message__error-title" part="message-error-title">${t}</div>`:""}
|
|
1999
2033
|
<div class="message__error-description" part="message-error-description">${n}</div>
|
|
2000
2034
|
</div>
|
|
2001
|
-
`}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}
|
|
2002
2058
|
</div>
|
|
2003
2059
|
${t.files&&t.files.length>0?i`
|
|
2004
2060
|
<div class="message__attachments" part="message-attachments" role="list" aria-label="${o.messages.attachedFilesLabel}">
|
|
@@ -2084,18 +2140,34 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2084
2140
|
${o.messages.retryButton}
|
|
2085
2141
|
</nr-button>`:e}
|
|
2086
2142
|
</div>
|
|
2087
|
-
`}function ft(t,n,o,s,r){return i`
|
|
2088
|
-
<div class="
|
|
2089
|
-
|
|
2143
|
+
`}function ft(t,n,o,s,r,a,l,c){const h=0===t.length?l?function(t){return i`
|
|
2144
|
+
<div class="empty-state empty-state--loading" part="empty-state thread-loading">
|
|
2145
|
+
<slot name="thread-loading">
|
|
2146
|
+
<div class="spinner" part="thread-loading-spinner"></div>
|
|
2147
|
+
<div class="empty-state__content" part="empty-state-content">
|
|
2148
|
+
${t.messages.loadingConversationLabel}
|
|
2149
|
+
</div>
|
|
2150
|
+
</slot>
|
|
2151
|
+
</div>
|
|
2152
|
+
`}(r):function(t,e){const n=null!=e?e:t.messages.startConversationLabel;return i`
|
|
2090
2153
|
<div class="empty-state" part="empty-state">
|
|
2091
2154
|
<slot name="empty-state">
|
|
2092
2155
|
<div class="empty-state__content" part="empty-state-content">
|
|
2093
|
-
${
|
|
2156
|
+
${n}
|
|
2094
2157
|
</div>
|
|
2095
2158
|
</slot>
|
|
2096
2159
|
</div>
|
|
2097
|
-
`}(r):e
|
|
2098
|
-
|
|
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)}
|
|
2099
2171
|
${n}
|
|
2100
2172
|
${o}
|
|
2101
2173
|
</div>
|
|
@@ -2389,7 +2461,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2389
2461
|
* @license
|
|
2390
2462
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2391
2463
|
* SPDX-License-Identifier: MIT
|
|
2392
|
-
*/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`
|
|
2393
2465
|
<div
|
|
2394
2466
|
class="thread-item ${a({"thread-item--active":t.id===e.activeThreadId})}"
|
|
2395
2467
|
@click=${()=>n.onSelectThread(t.id)}
|
|
@@ -2448,7 +2520,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2448
2520
|
</div>
|
|
2449
2521
|
<div class="thread-item__timestamp" part="thread-timestamp">${rt(t.updatedAt)}</div>
|
|
2450
2522
|
</div>
|
|
2451
|
-
`}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`
|
|
2452
2524
|
<nr-modal
|
|
2453
2525
|
.open=${t.isOpen}
|
|
2454
2526
|
size="large"
|
|
@@ -2558,7 +2630,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2558
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}
|
|
2559
2631
|
</div>
|
|
2560
2632
|
</div>
|
|
2561
|
-
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,n.message,t.i18n)}
|
|
2633
|
+
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,n.message,t.i18n,t.welcomeMessage,t.isPendingThread,t.invertedScroll)}
|
|
2562
2634
|
<slot name="messages"></slot>
|
|
2563
2635
|
</div>
|
|
2564
2636
|
`:t.suggestions&&t.suggestions.length>0?i`
|
|
@@ -2586,14 +2658,14 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2586
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>
|
|
2587
2659
|
${t.i18n.threads.bookmarksLabel}
|
|
2588
2660
|
</div>
|
|
2589
|
-
${d(o,t=>t.id,e=>
|
|
2661
|
+
${d(o,t=>t.id,e=>xt(e,t,n))}
|
|
2590
2662
|
</div>
|
|
2591
2663
|
`:e}
|
|
2592
2664
|
${s.length>0||0===o.length?i`
|
|
2593
2665
|
${o.length>0?i`
|
|
2594
2666
|
<div class="thread-section__label" part="thread-section-label">${t.i18n.threads.allConversationsLabel}</div>
|
|
2595
2667
|
`:e}
|
|
2596
|
-
${d(s,t=>t.id,e=>
|
|
2668
|
+
${d(s,t=>t.id,e=>xt(e,t,n))}
|
|
2597
2669
|
${0===s.length&&0===o.length?i`
|
|
2598
2670
|
<p class="empty-msg" part="thread-empty">${t.i18n.threads.noConversationsLabel}</p>
|
|
2599
2671
|
`:e}
|
|
@@ -2633,11 +2705,13 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2633
2705
|
</div>
|
|
2634
2706
|
`:e}(t,n)}
|
|
2635
2707
|
|
|
2636
|
-
<
|
|
2708
|
+
<div class="chatbot-boxed-area" part="boxed-area">
|
|
2709
|
+
<slot name="header"></slot>
|
|
2637
2710
|
|
|
2638
|
-
|
|
2711
|
+
${_t(t,n)}
|
|
2639
2712
|
|
|
2640
|
-
|
|
2713
|
+
${bt(t.inputBox,n.inputBox)}
|
|
2714
|
+
</div>
|
|
2641
2715
|
|
|
2642
2716
|
<slot name="footer"></slot>
|
|
2643
2717
|
</div>
|
|
@@ -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: ")},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 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()}if(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)}}handleControllerStateChange(t){var e,i,n,o,s;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&&(this.activeThreadId=t.currentThreadId),this.enableUrlSync&&t.currentThreadId){const e=`#conversation/${encodeURIComponent(t.currentThreadId)}`;window.location.hash!==e&&history.replaceState(null,"",e)}if(this.chatStarted=(null===(e=t.messages)||void 0===e?void 0:e.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===(i=t.messages)||void 0===i?void 0:i.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===(n=t.messages)||void 0===n?void 0:n.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),i=null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.artifactIds;if(null==i?void 0:i.length){const t=i[i.length-1];if((null===(s=this.selectedArtifact)||void 0===s?void 0:s.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,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.enableFileUpload,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;this.enableUrlSync&&history.pushState(null,"",`#conversation/${encodeURIComponent(t)}`),null===(e=this.controller)||void 0===e||e.switchThread(t)},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,18 +2860,18 @@ 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})],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: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),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
|
|
2793
2867
|
* SPDX-License-Identifier: MIT
|
|
2794
2868
|
*/
|
|
2795
|
-
class
|
|
2869
|
+
class zt{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var i,n;null===(i=this.listeners.get(t))||void 0===i||i.delete(e),0===(null===(n=this.listeners.get(t))||void 0===n?void 0:n.size)&&this.listeners.delete(t)}}once(t,e){const i=(...n)=>{e(...n),this.off(t,i)};this.on(t,i)}off(t,e){var i;null===(i=this.listeners.get(t))||void 0===i||i.delete(e)}emit(t,e){const i=this.listeners.get(t);i&&i.forEach(i=>{try{i(e)}catch(e){console.error(`Error in event handler for "${t}":`,e)}})}removeAllListeners(t){t?this.listeners.delete(t):this.listeners.clear()}listenerCount(t){var e;return(null===(e=this.listeners.get(t))||void 0===e?void 0:e.size)||0}eventNames(){return Array.from(this.listeners.keys())}}
|
|
2796
2870
|
/**
|
|
2797
2871
|
* @license
|
|
2798
2872
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2799
2873
|
* SPDX-License-Identifier: MIT
|
|
2800
|
-
*/class
|
|
2874
|
+
*/class Ot extends Error{constructor(t){super(t.join(", ")),this.errors=t,this.name="ValidationError"}}
|
|
2801
2875
|
/**
|
|
2802
2876
|
* @license
|
|
2803
2877
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
@@ -2853,7 +2927,7 @@ class Ot{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(
|
|
|
2853
2927
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2854
2928
|
* SPDX-License-Identifier: MIT
|
|
2855
2929
|
*/
|
|
2856
|
-
var Qt=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())})};class Xt{constructor(t={}){this.plugins=new Map,this.config=t,this.ui=t.ui||{},this.eventBus=new Ot,this.pluginService=new Gt,this.plugins=this.pluginService.getPluginsMap(),t.plugins&&t.plugins.forEach(t=>this.pluginService.registerPlugin(t,this));const e=this.initializeState(t);if(this.stateHandler=new It(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new jt(this.stateHandler,this.eventBus,this.plugins),this.threadHandler=new At(this.stateHandler,this.eventBus,this.ui,this.config,t.provider),this.fileHandler=new Ft(this.stateHandler,this.eventBus),this.moduleHandler=new Dt(this.stateHandler,this.eventBus),this.suggestionHandler=new Bt(this.stateHandler),this.providerService=new Ut(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new Ht(this.config),this.storageService=new qt(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Qt(this,void 0,void 0,function*(){try{t.isConnected()||(yield t.connect({})),yield this.autoLoadConversations(t)}catch(t){this.logError("Failed to connect provider:",t)}})}initializeState(t){const e=t.initialMessages?t.initialMessages.map(t=>this.processMessageThroughPlugins(t)):[];return{messages:e,threads:t.initialThreads||[],modules:t.enableModules?[]:void 0,selectedModules:[],uploadedFiles:[],suggestions:t.initialSuggestions||[],isTyping:!1,isProcessing:!1,currentThreadId:void 0,metadata:t.metadata||{}}}processMessageThroughPlugins(t){if(!t.text||"string"!=typeof t.text)return t;const e=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)&&t.htmlTags.length>0);if(0===e.length)return t;let i=t.text,n=!1;for(const t of e){const e=t.htmlTags;for(const o of e){const e=o.open,s=o.close;let r=0;for(;;){const a=i.indexOf(e,r);if(-1===a)break;const l=a+e.length,d=i.indexOf(s,l);if(-1===d){r=l;continue}const c=i.substring(l,d);let h="";if("function"==typeof t.renderHtmlBlock)try{h=t.renderHtmlBlock(o.name,c)}catch(e){console.error(`[ChatbotCore] Error rendering HTML block for plugin ${t.id}:`,e)}h?(i=i.substring(0,a)+h+i.substring(d+s.length),n=!0,r=a+h.length):r=d+s.length}}}return n?Object.assign(Object.assign({},t),{text:i,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0})}):t}processRestoredMessagesForPlugins(){const t=this.stateHandler.getState();if(t.messages&&0!==t.messages.length)for(const e of t.messages)"bot"===e.sender&&this.plugins.forEach(t=>{if(t.onMessageReceived)try{t.onMessageReceived(e)}catch(t){}})}setupLifecycleHooks(){this.onBeforeInit(),this.onReady().catch(t=>{this.logError("Error during initialization:",t)})}onBeforeInit(){this.log("Initializing chatbot controller...")}onReady(){return Qt(this,void 0,void 0,function*(){this.log("Chatbot controller ready");try{const t=this.stateHandler.getState(),e=t.messages&&t.messages.length>0?t.messages[0]:void 0;e&&"bot"===e.sender&&e.introduction&&Array.isArray(e.suggestions)&&e.suggestions.length>0&&this.suggestionHandler.setSuggestions(e.suggestions)}catch(t){this.logError("Error initializing suggestions from initial messages:",t)}this.processRestoredMessagesForPlugins(),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.emit("ready",this.stateHandler.getState())})}onDestroy(){this.log("Destroying chatbot controller..."),this.storageService.stopAutoSave(),this.pluginService.clearPlugins(),this.eventBus.removeAllListeners()}updateState(t){this.stateHandler.updateState(t)}sendMessage(t){return Qt(this,arguments,void 0,function*(t,e={}){this.log("Sending message:",t);try{const i=this.stateHandler.getState();this.config.enableThreads&&!i.currentThreadId&&(yield this.threadHandler.createThread("New Chat"));const n=yield this.beforeMessageSent(t,e);if(!e.skipValidation){const t=yield this.validationService.validateMessage(n);if(!t.isValid){const e=new zt(t.errors);throw this.handleValidationError(e),e}}const o=this.messageHandler.createUserMessage(n,e.metadata);e.files&&(o.files=e.files),this.messageHandler.addMessage(o);const s=this.stateHandler.getState();return(e.threadId||s.currentThreadId)&&this.threadHandler.updateThreadMessages(e.threadId||s.currentThreadId),yield this.afterMessageSent(o),this.providerService.processMessage(o).catch(t=>{this.logError("Error processing with provider:",t)}),o}catch(t){throw this.handleError(t),t}})}stop(){this.providerService.stopCurrentProcessing()}addMessage(t){const e=this.messageHandler.createMessage(t),i="bot"===e.sender?this.processMessageThroughPlugins(e):e;return this.messageHandler.addMessage(i),i}updateMessage(t,e){this.messageHandler.updateMessage(t,e)}deleteMessage(t){this.messageHandler.deleteMessage(t)}clearMessages(){this.updateState({messages:[]})}getMessages(){return this.stateHandler.getState().messages}uploadFiles(t){return Qt(this,void 0,void 0,function*(){if(!this.config.enableFileUpload)throw new Error("File upload is not enabled");let e=t;if(!e&&this.ui.openFileDialog&&(e=yield this.ui.openFileDialog()),!e||0===e.length)return[];const i=[];for(const t of e)try{const e=yield this.validationService.validateFile(t,{maxFileSize:this.config.maxFileSize,allowedTypes:this.config.allowedFileTypes});if(!e.isValid){this.ui.showNotification&&this.ui.showNotification(e.errors[0]||"File validation failed","error");continue}const n=yield this.fileHandler.createChatbotFile(t);this.fileHandler.addFile(n);try{const e=yield this.providerService.uploadFileToProvider(t),o=Object.assign({isUploading:!1,uploadProgress:100},e||{});this.fileHandler.updateFile(n.id,o),Object.assign(n,o),i.push(n),this.ui.showFilePreview&&this.ui.showFilePreview(n)}catch(t){throw this.fileHandler.removeFile(n.id),t}}catch(e){this.logError("Error uploading file:",e),this.ui.showNotification&&this.ui.showNotification(`Failed to upload ${t.name}`,"error")}return i})}removeFile(t){this.fileHandler.removeFile(t)}clearFiles(){this.fileHandler.clearFiles()}getUploadedFiles(){return this.stateHandler.getState().uploadedFiles}createThread(t){return Qt(this,void 0,void 0,function*(){return yield this.threadHandler.createThread(t)})}switchThread(t){this.threadHandler.switchThread(t),this.processRestoredMessagesForPlugins()}deleteThread(t){this.threadHandler.deleteThread(t)}renameThread(t,e){this.threadHandler.renameThread(t,e)}bookmarkThread(t){this.threadHandler.bookmarkThread(t)}getCurrentThread(){const t=this.stateHandler.getState();return t.threads.find(e=>e.id===t.currentThreadId)}getThreads(){return this.stateHandler.getState().threads}setModules(t){this.moduleHandler.setModules(t)}selectModules(t){this.moduleHandler.selectModules(t)}toggleModule(t){this.moduleHandler.toggleModule(t)}getSelectedModules(){return this.moduleHandler.getSelectedModules()}setSuggestions(t){this.suggestionHandler.setSuggestions(t)}clearSuggestions(){this.suggestionHandler.clearSuggestions()}beforeMessageSent(t,e){return Qt(this,void 0,void 0,function*(){let e=t;for(const t of this.plugins.values())t.beforeSend&&(e=yield t.beforeSend(e));return e})}afterMessageSent(t){return Qt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Qt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Qt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Qt(this,void 0,void 0,function*(){this.logError("Provider error:",t);const e=this.messageHandler.createMessage({sender:q.Bot,text:"Sorry, there was an error processing your request.",state:Y.Error,timestamp:(new Date).toISOString()});this.messageHandler.addMessage(e),this.ui.showNotification&&this.ui.showNotification("Failed to process message","error"),this.emit("provider:error",t),yield this.pluginService.executeHook("onError",t)})}handleValidationError(t){this.logError("Validation error:",t),this.ui.showNotification&&this.ui.showNotification(t.errors[0],"error"),this.emit("validation:error",t)}handleError(t){this.logError("Error:",t),this.emit("error",t),this.plugins.forEach(e=>{e.onError&&e.onError(t)})}registerPlugin(t){this.pluginService.registerPlugin(t,this)}unregisterPlugin(t){this.pluginService.unregisterPlugin(t)}getPlugin(t){return this.pluginService.getPlugin(t)}setProvider(t){this.providerService.setProvider(t),t.isConnected()?(this.autoLoadConversations(t).catch(t=>{this.logError("Failed to auto-load conversations:",t)}),this.emit("provider:connected",t.id)):t.connect({}).then(()=>Qt(this,void 0,void 0,function*(){yield this.autoLoadConversations(t),this.emit("provider:connected",t.id)})).catch(t=>{this.logError("Failed to connect provider:",t)})}setStorage(t){this.storageService.setStorage(t)}saveToStorage(){return Qt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Qt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.loadState(t);const e=this.stateHandler.getState();if(e.messages&&e.messages.length>0){const t=e.messages.map(t=>this.processMessageThroughPlugins(t));this.stateHandler.updateState({messages:t}),this.processRestoredMessagesForPlugins()}})}on(t,e){return this.eventBus.on(t,e)}emit(t,e){this.eventBus.emit(t,e)}getState(){return this.stateHandler.getState()}setState(t){t.messages&&Array.isArray(t.messages)&&(t.messages=t.messages.map(t=>this.processMessageThroughPlugins(t))),t.threads&&Array.isArray(t.threads)&&(t.threads=t.threads.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}))),this.updateState(t),t.messages&&this.processRestoredMessagesForPlugins()}loadConversations(t){const e=t.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}));this.updateState({threads:e,currentThreadId:e.length>0?e[0].id:void 0,messages:e.length>0?e[0].messages:[]}),this.processRestoredMessagesForPlugins()}autoLoadConversations(t){return Qt(this,void 0,void 0,function*(){if(t&&"function"==typeof t.loadConversations)try{this.log("Auto-loading conversations from provider...");const e=yield t.loadConversations();if(Array.isArray(e)&&e.length>0){this.log(`Loaded ${e.length} conversation summaries`);const i=[];if("function"==typeof t.loadConversation)for(const n of e)try{const e=yield t.loadConversation(n.id);if(e){const t={id:e.id,title:e.title,messages:e.messages||[],createdAt:e.createdAt,updatedAt:e.updatedAt};i.push(t)}}catch(t){this.logError(`Failed to load conversation ${n.id}:`,t)}else for(const t of e){const e={id:t.id,title:t.title,messages:[],createdAt:t.createdAt,updatedAt:t.updatedAt};i.push(e)}i.length>0&&(this.log(`Successfully loaded ${i.length} conversations`),this.loadConversations(i))}else this.log("No conversations to load from provider")}catch(t){this.logError("Failed to auto-load conversations from provider:",t)}})}setUICallbacks(t){this.ui=Object.assign(Object.assign({},this.ui),t)}getConfig(){return Object.freeze(Object.assign({},this.config))}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t)}setTyping(t){this.updateState({isTyping:t}),this.emit(t?"typing:start":"typing:end")}setStatusText(t){this.updateState({statusText:t})}clearStatusText(){this.updateState({statusText:void 0})}getContext(){const t=this.stateHandler.getState();return{messages:t.messages,currentThread:this.getCurrentThread(),selectedModules:t.selectedModules,metadata:t.metadata,uploadedFiles:t.uploadedFiles}}destroy(){this.onDestroy()}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}formatFileSize(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}log(...t){this.config.debug&&console.log("[ChatbotCore]",...t)}logError(...t){console.error("[ChatbotCore]",...t)}}
|
|
2930
|
+
var Qt=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())})};class Xt{constructor(t={}){this.plugins=new Map,this.config=t,this.ui=t.ui||{},this.eventBus=new zt,this.pluginService=new Gt,this.plugins=this.pluginService.getPluginsMap(),t.plugins&&t.plugins.forEach(t=>this.pluginService.registerPlugin(t,this));const e=this.initializeState(t);if(this.stateHandler=new It(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new jt(this.stateHandler,this.eventBus,this.plugins),this.threadHandler=new At(this.stateHandler,this.eventBus,this.ui,this.config,t.provider),this.fileHandler=new Ft(this.stateHandler,this.eventBus),this.moduleHandler=new Dt(this.stateHandler,this.eventBus),this.suggestionHandler=new Bt(this.stateHandler),this.providerService=new Ut(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new Ht(this.config),this.storageService=new qt(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Qt(this,void 0,void 0,function*(){try{t.isConnected()||(yield t.connect({})),yield this.autoLoadConversations(t)}catch(t){this.logError("Failed to connect provider:",t)}})}initializeState(t){const e=t.initialMessages?t.initialMessages.map(t=>this.processMessageThroughPlugins(t)):[];return{messages:e,threads:t.initialThreads||[],modules:t.enableModules?[]:void 0,selectedModules:[],uploadedFiles:[],suggestions:t.initialSuggestions||[],isTyping:!1,isProcessing:!1,currentThreadId:void 0,metadata:t.metadata||{}}}processMessageThroughPlugins(t){if(!t.text||"string"!=typeof t.text)return t;const e=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)&&t.htmlTags.length>0);if(0===e.length)return t;let i=t.text,n=!1;for(const t of e){const e=t.htmlTags;for(const o of e){const e=o.open,s=o.close;let r=0;for(;;){const a=i.indexOf(e,r);if(-1===a)break;const l=a+e.length,d=i.indexOf(s,l);if(-1===d){r=l;continue}const c=i.substring(l,d);let h="";if("function"==typeof t.renderHtmlBlock)try{h=t.renderHtmlBlock(o.name,c)}catch(e){console.error(`[ChatbotCore] Error rendering HTML block for plugin ${t.id}:`,e)}h?(i=i.substring(0,a)+h+i.substring(d+s.length),n=!0,r=a+h.length):r=d+s.length}}}return n?Object.assign(Object.assign({},t),{text:i,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0})}):t}processRestoredMessagesForPlugins(){const t=this.stateHandler.getState();if(t.messages&&0!==t.messages.length)for(const e of t.messages)"bot"===e.sender&&this.plugins.forEach(t=>{if(t.onMessageReceived)try{t.onMessageReceived(e)}catch(t){}})}setupLifecycleHooks(){this.onBeforeInit(),this.onReady().catch(t=>{this.logError("Error during initialization:",t)})}onBeforeInit(){this.log("Initializing chatbot controller...")}onReady(){return Qt(this,void 0,void 0,function*(){this.log("Chatbot controller ready");try{const t=this.stateHandler.getState(),e=t.messages&&t.messages.length>0?t.messages[0]:void 0;e&&"bot"===e.sender&&e.introduction&&Array.isArray(e.suggestions)&&e.suggestions.length>0&&this.suggestionHandler.setSuggestions(e.suggestions)}catch(t){this.logError("Error initializing suggestions from initial messages:",t)}this.processRestoredMessagesForPlugins(),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.emit("ready",this.stateHandler.getState())})}onDestroy(){this.log("Destroying chatbot controller..."),this.storageService.stopAutoSave(),this.pluginService.clearPlugins(),this.eventBus.removeAllListeners()}updateState(t){this.stateHandler.updateState(t)}sendMessage(t){return Qt(this,arguments,void 0,function*(t,e={}){this.log("Sending message:",t);try{const i=this.stateHandler.getState();this.config.enableThreads&&!i.currentThreadId&&(yield this.threadHandler.createThread("New Chat"));const n=yield this.beforeMessageSent(t,e);if(!e.skipValidation){const t=yield this.validationService.validateMessage(n);if(!t.isValid){const e=new Ot(t.errors);throw this.handleValidationError(e),e}}const o=this.messageHandler.createUserMessage(n,e.metadata);e.files&&(o.files=e.files),this.messageHandler.addMessage(o);const s=this.stateHandler.getState();return(e.threadId||s.currentThreadId)&&this.threadHandler.updateThreadMessages(e.threadId||s.currentThreadId),yield this.afterMessageSent(o),this.providerService.processMessage(o).catch(t=>{this.logError("Error processing with provider:",t)}),o}catch(t){throw this.handleError(t),t}})}stop(){this.providerService.stopCurrentProcessing()}addMessage(t){const e=this.messageHandler.createMessage(t),i="bot"===e.sender?this.processMessageThroughPlugins(e):e;return this.messageHandler.addMessage(i),i}updateMessage(t,e){this.messageHandler.updateMessage(t,e)}deleteMessage(t){this.messageHandler.deleteMessage(t)}clearMessages(){this.updateState({messages:[]})}getMessages(){return this.stateHandler.getState().messages}uploadFiles(t){return Qt(this,void 0,void 0,function*(){if(!this.config.enableFileUpload)throw new Error("File upload is not enabled");let e=t;if(!e&&this.ui.openFileDialog&&(e=yield this.ui.openFileDialog()),!e||0===e.length)return[];const i=[];for(const t of e)try{const e=yield this.validationService.validateFile(t,{maxFileSize:this.config.maxFileSize,allowedTypes:this.config.allowedFileTypes});if(!e.isValid){this.ui.showNotification&&this.ui.showNotification(e.errors[0]||"File validation failed","error");continue}const n=yield this.fileHandler.createChatbotFile(t);this.fileHandler.addFile(n);try{const e=yield this.providerService.uploadFileToProvider(t),o=Object.assign({isUploading:!1,uploadProgress:100},e||{});this.fileHandler.updateFile(n.id,o),Object.assign(n,o),i.push(n),this.ui.showFilePreview&&this.ui.showFilePreview(n)}catch(t){throw this.fileHandler.removeFile(n.id),t}}catch(e){this.logError("Error uploading file:",e),this.ui.showNotification&&this.ui.showNotification(`Failed to upload ${t.name}`,"error")}return i})}removeFile(t){this.fileHandler.removeFile(t)}clearFiles(){this.fileHandler.clearFiles()}getUploadedFiles(){return this.stateHandler.getState().uploadedFiles}createThread(t){return Qt(this,void 0,void 0,function*(){return yield this.threadHandler.createThread(t)})}switchThread(t){this.threadHandler.switchThread(t),this.processRestoredMessagesForPlugins()}deleteThread(t){this.threadHandler.deleteThread(t)}renameThread(t,e){this.threadHandler.renameThread(t,e)}bookmarkThread(t){this.threadHandler.bookmarkThread(t)}getCurrentThread(){const t=this.stateHandler.getState();return t.threads.find(e=>e.id===t.currentThreadId)}getThreads(){return this.stateHandler.getState().threads}setModules(t){this.moduleHandler.setModules(t)}selectModules(t){this.moduleHandler.selectModules(t)}toggleModule(t){this.moduleHandler.toggleModule(t)}getSelectedModules(){return this.moduleHandler.getSelectedModules()}setSuggestions(t){this.suggestionHandler.setSuggestions(t)}clearSuggestions(){this.suggestionHandler.clearSuggestions()}beforeMessageSent(t,e){return Qt(this,void 0,void 0,function*(){let e=t;for(const t of this.plugins.values())t.beforeSend&&(e=yield t.beforeSend(e));return e})}afterMessageSent(t){return Qt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Qt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Qt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Qt(this,void 0,void 0,function*(){this.logError("Provider error:",t);const e=this.messageHandler.createMessage({sender:q.Bot,text:"Sorry, there was an error processing your request.",state:Y.Error,timestamp:(new Date).toISOString()});this.messageHandler.addMessage(e),this.ui.showNotification&&this.ui.showNotification("Failed to process message","error"),this.emit("provider:error",t),yield this.pluginService.executeHook("onError",t)})}handleValidationError(t){this.logError("Validation error:",t),this.ui.showNotification&&this.ui.showNotification(t.errors[0],"error"),this.emit("validation:error",t)}handleError(t){this.logError("Error:",t),this.emit("error",t),this.plugins.forEach(e=>{e.onError&&e.onError(t)})}registerPlugin(t){this.pluginService.registerPlugin(t,this)}unregisterPlugin(t){this.pluginService.unregisterPlugin(t)}getPlugin(t){return this.pluginService.getPlugin(t)}setProvider(t){this.providerService.setProvider(t),t.isConnected()?(this.autoLoadConversations(t).catch(t=>{this.logError("Failed to auto-load conversations:",t)}),this.emit("provider:connected",t.id)):t.connect({}).then(()=>Qt(this,void 0,void 0,function*(){yield this.autoLoadConversations(t),this.emit("provider:connected",t.id)})).catch(t=>{this.logError("Failed to connect provider:",t)})}setStorage(t){this.storageService.setStorage(t)}saveToStorage(){return Qt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Qt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.loadState(t);const e=this.stateHandler.getState();if(e.messages&&e.messages.length>0){const t=e.messages.map(t=>this.processMessageThroughPlugins(t));this.stateHandler.updateState({messages:t}),this.processRestoredMessagesForPlugins()}})}on(t,e){return this.eventBus.on(t,e)}emit(t,e){this.eventBus.emit(t,e)}getState(){return this.stateHandler.getState()}setState(t){t.messages&&Array.isArray(t.messages)&&(t.messages=t.messages.map(t=>this.processMessageThroughPlugins(t))),t.threads&&Array.isArray(t.threads)&&(t.threads=t.threads.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}))),this.updateState(t),t.messages&&this.processRestoredMessagesForPlugins()}loadConversations(t){const e=t.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}));this.updateState({threads:e,currentThreadId:e.length>0?e[0].id:void 0,messages:e.length>0?e[0].messages:[]}),this.processRestoredMessagesForPlugins()}autoLoadConversations(t){return Qt(this,void 0,void 0,function*(){if(t&&"function"==typeof t.loadConversations)try{this.log("Auto-loading conversations from provider...");const e=yield t.loadConversations();if(Array.isArray(e)&&e.length>0){this.log(`Loaded ${e.length} conversation summaries`);const i=[];if("function"==typeof t.loadConversation)for(const n of e)try{const e=yield t.loadConversation(n.id);if(e){const t={id:e.id,title:e.title,messages:e.messages||[],createdAt:e.createdAt,updatedAt:e.updatedAt};i.push(t)}}catch(t){this.logError(`Failed to load conversation ${n.id}:`,t)}else for(const t of e){const e={id:t.id,title:t.title,messages:[],createdAt:t.createdAt,updatedAt:t.updatedAt};i.push(e)}i.length>0&&(this.log(`Successfully loaded ${i.length} conversations`),this.loadConversations(i))}else this.log("No conversations to load from provider")}catch(t){this.logError("Failed to auto-load conversations from provider:",t)}})}setUICallbacks(t){this.ui=Object.assign(Object.assign({},this.ui),t)}getConfig(){return Object.freeze(Object.assign({},this.config))}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t)}setTyping(t){this.updateState({isTyping:t}),this.emit(t?"typing:start":"typing:end")}setStatusText(t){this.updateState({statusText:t})}clearStatusText(){this.updateState({statusText:void 0})}getContext(){const t=this.stateHandler.getState();return{messages:t.messages,currentThread:this.getCurrentThread(),selectedModules:t.selectedModules,metadata:t.metadata,uploadedFiles:t.uploadedFiles}}destroy(){this.onDestroy()}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}formatFileSize(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}log(...t){this.config.debug&&console.log("[ChatbotCore]",...t)}logError(...t){console.error("[ChatbotCore]",...t)}}
|
|
2857
2931
|
/**
|
|
2858
2932
|
* @license
|
|
2859
2933
|
* 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
|
|
@@ -2893,47 +2967,47 @@ var Qt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
|
|
|
2893
2967
|
* @license
|
|
2894
2968
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2895
2969
|
* SPDX-License-Identifier: MIT
|
|
2896
|
-
*/class
|
|
2970
|
+
*/class ze{constructor(t){this.id="analytics",this.name="Analytics Plugin",this.version="1.0.0",this.trackEvent=t}onInit(){this.trackEvent("chatbot:initialized",{timestamp:(new Date).toISOString()}),console.log("[AnalyticsPlugin] Initialized")}onDestroy(){this.trackEvent("chatbot:destroyed",{timestamp:(new Date).toISOString()}),console.log("[AnalyticsPlugin] Destroyed")}onMessageSent(t){this.trackEvent("chatbot:message:sent",{messageId:t.id,messageLength:t.text.length,hasFiles:!!t.files&&t.files.length>0,timestamp:t.timestamp})}onMessageReceived(t){this.trackEvent("chatbot:message:received",{messageId:t.id,messageLength:t.text.length,sender:t.sender,timestamp:t.timestamp})}onError(t){this.trackEvent("chatbot:error",{error:t.message,stack:t.stack,timestamp:(new Date).toISOString()})}}
|
|
2897
2971
|
/**
|
|
2898
2972
|
* @license
|
|
2899
2973
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2900
2974
|
* SPDX-License-Identifier: MIT
|
|
2901
|
-
*/class
|
|
2975
|
+
*/class Oe{constructor(){this._stylesInjected=!1}getOncePerConversationStyleTag(t,e="nr-chatbot"){var i;const n=`data-plugin-styles-${this.id}`;let o=!1;try{const t=document.querySelector(e);o=!!(null===(i=null==t?void 0:t.shadowRoot)||void 0===i?void 0:i.querySelector(`style[${n}]`))}catch(t){}return this._stylesInjected||o?"":(this._stylesInjected=!0,`<style ${n}="true">${t}</style>`)}onStateChange(t){try{const e=null==t?void 0:t.currentThreadId;e!==this._lastThreadId&&(this._lastThreadId=e,this._stylesInjected=!1)}catch(t){}}}
|
|
2902
2976
|
/**
|
|
2903
2977
|
* @license
|
|
2904
2978
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2905
2979
|
* SPDX-License-Identifier: MIT
|
|
2906
|
-
*/var Ie=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())})};class je extends
|
|
2980
|
+
*/var Ie=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())})};class je extends Oe{constructor(){super(...arguments),this.id="markdown",this.name="Markdown Plugin",this.version="2.0.0",this.htmlTags=[{name:"md",open:"[MD]",close:"[/MD]"}]}onInit(){console.log("[MarkdownPlugin] Initialized")}renderHtmlBlock(t,e){if("md"!==t)return"";const i=this.getStyles();return`${this.getOncePerConversationStyleTag(i)}${ct(e)}`}afterReceive(t){return Ie(this,void 0,void 0,function*(){return t.includes("[MD]")&&t.includes("[/MD]")?t:ct(t)})}getStyles(){return"\n .md-code { background: #f6f8fa; padding: 12px; border-radius: 6px; overflow: auto; }\n .md-inline-code { background: rgba(27,31,35,.05); padding: 0 4px; border-radius: 4px; }\n h1, h2, h3 { margin: 0.6em 0 0.4em; font-weight: 600; }\n p { margin: 0.5em 0; }\n ul { margin: 0.5em 0 0.5em 1.2em; }\n a { color: #0b5fff; text-decoration: underline; }\n "}}
|
|
2907
2981
|
/**
|
|
2908
2982
|
* @license
|
|
2909
2983
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2910
2984
|
* SPDX-License-Identifier: MIT
|
|
2911
|
-
*/var Re=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())})};class Ae extends ze{constructor(){super(...arguments),this.id="flight-card",this.name="Flight Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"flight",open:"[FLIGHT]",close:"[/FLIGHT]"}],this.cssPrefix="nr-flight-card"}renderHtmlBlockPlaceholder(t){if("flight"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`flight-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n style="min-width: 400px; max-width: 600px; margin: 16px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[FlightCardPlugin] Initialized")}afterReceive(t){return Re(this,void 0,void 0,function*(){try{const e=JSON.parse(t);if("flight"===e.type||this.isFlightData(e))return this.renderFlightCard(e)}catch(t){}const e=/\[FLIGHT\]([\s\S]*?)\[\/FLIGHT\]/g;let i,n=t;for(;null!==(i=e.exec(t));)try{const t=JSON.parse(i[1]),e=this.renderFlightCard(t);n=n.replace(i[0],e)}catch(t){console.warn("[FlightCardPlugin] Failed to parse flight data:",t)}return n})}renderHtmlBlock(t,e){if("flight"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderFlightCard(t)}catch(t){return console.warn("[FlightCardPlugin] renderHtmlBlock parse error:",t),""}}isFlightData(t){return t&&"object"==typeof t&&t.origin&&t.destination&&t.departureTime}renderFlightCard(t){const{origin:e,destination:i,departureTime:n,arrivalTime:o,departureDate:s,arrivalDate:r,terminal:a,gate:l,arrivalTerminal:d,arrivalGate:c,duration:h,flightNumber:u,airline:p,status:f,updated:m,source:g}=t;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-flight-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__route">\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(e)}</span>\n <div class="${this.cssPrefix}__flight-line">\n <svg class="${this.cssPrefix}__plane-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" fill="currentColor"/>\n </svg>\n ${h?`<span class="${this.cssPrefix}__duration">${this.escapeHtml(h)}</span>`:""}\n </div>\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(i)}</span>\n </div>\n ${u||p?`\n <div class="${this.cssPrefix}__flight-info">\n ${p?`<span class="${this.cssPrefix}__airline">${this.escapeHtml(p)}</span>`:""}\n ${u?`<span class="${this.cssPrefix}__flight-number">${this.escapeHtml(u)}</span>`:""}\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--departure">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(e)}</span>\n <span class="${this.cssPrefix}__date">${s?this.escapeHtml(s):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure de départ prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(n)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${a?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(a)}</span>\n </div>\n `:""}\n ${l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(l)}</span>\n </div>\n `:void 0===l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n\n <div class="${this.cssPrefix}__divider"></div>\n\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--arrival">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(i)}</span>\n <span class="${this.cssPrefix}__date">${r?this.escapeHtml(r):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure d'arrivée prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(o)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${d?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(d)}</span>\n </div>\n `:""}\n ${c?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(c)}</span>\n </div>\n `:void 0===c?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n </div>\n\n ${m||g||f?`\n <div class="${this.cssPrefix}__footer">\n ${m?`<span class="${this.cssPrefix}__updated">${this.escapeHtml(m)}</span>`:""}\n ${g?`<span class="${this.cssPrefix}__source">Source : ${this.escapeHtml(g)}</span>`:""}\n ${f?`<span class="${this.cssPrefix}__status">${this.escapeHtml(f)}</span>`:""}\n </div>\n `:""}\n </div>\n `}getCityName(t){return{JED:"Djeddah",TUN:"Tunis",CDG:"Paris",LHR:"London",JFK:"New York",DXB:"Dubai",LAX:"Los Angeles",ORD:"Chicago",ATL:"Atlanta",DFW:"Dallas",DEN:"Denver",SFO:"San Francisco",SEA:"Seattle",LAS:"Las Vegas",MCO:"Orlando",MIA:"Miami",IAH:"Houston",PHX:"Phoenix",BOS:"Boston",MSP:"Minneapolis",DTW:"Detroit",FLL:"Fort Lauderdale",PHL:"Philadelphia",LGA:"New York",BWI:"Baltimore",SLC:"Salt Lake City",SAN:"San Diego",DCA:"Washington",TPA:"Tampa",PDX:"Portland",STL:"St. Louis"}[t.toUpperCase()]||t}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 24px;\n margin: 16px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 600px;\n }\n\n .${this.cssPrefix}__header {\n margin-bottom: 24px;\n }\n\n .${this.cssPrefix}__route {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__airport-code {\n font-size: 32px;\n font-weight: 700;\n color: #1a1a1a;\n letter-spacing: 0.5px;\n }\n\n .${this.cssPrefix}__flight-line {\n flex: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n padding: 0 16px;\n }\n\n .${this.cssPrefix}__flight-line::before {\n content: '';\n position: absolute;\n top: 50%;\n left: 0;\n right: 0;\n height: 2px;\n background: linear-gradient(to right, #e0e0e0 0%, #e0e0e0 100%);\n z-index: 0;\n }\n\n .${this.cssPrefix}__plane-icon {\n width: 24px;\n height: 24px;\n color: #666;\n background: white;\n padding: 4px;\n position: relative;\n z-index: 1;\n transform: rotate(90deg);\n }\n\n .${this.cssPrefix}__duration {\n position: absolute;\n top: -24px;\n background: white;\n padding: 2px 8px;\n font-size: 13px;\n color: #666;\n white-space: nowrap;\n }\n\n .${this.cssPrefix}__flight-info {\n display: flex;\n gap: 8px;\n align-items: center;\n font-size: 14px;\n color: #666;\n }\n\n .${this.cssPrefix}__airline {\n font-weight: 500;\n }\n\n .${this.cssPrefix}__flight-number {\n color: #999;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: 1fr auto 1fr;\n gap: 24px;\n }\n\n .${this.cssPrefix}__divider {\n width: 1px;\n background: #e0e0e0;\n }\n\n .${this.cssPrefix}__section {\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .${this.cssPrefix}__label {\n font-size: 12px;\n color: #999;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n font-weight: 500;\n text-decoration: underline;\n }\n\n .${this.cssPrefix}__location {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__city {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__date {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__time-group {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__time-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__time-value {\n font-size: 24px;\n font-weight: 700;\n color: #2d6a3e;\n }\n\n .${this.cssPrefix}__terminal-gate {\n display: flex;\n gap: 16px;\n }\n\n .${this.cssPrefix}__info-item {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__info-label {\n font-size: 11px;\n color: #999;\n }\n\n .${this.cssPrefix}__info-value {\n font-size: 18px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n margin-top: 16px;\n padding-top: 16px;\n border-top: 1px solid #e0e0e0;\n display: flex;\n justify-content: space-between;\n align-items: center;\n font-size: 12px;\n color: #666;\n gap: 12px;\n }\n\n .${this.cssPrefix}__updated {\n color: #999;\n }\n\n .${this.cssPrefix}__source {\n color: #666;\n }\n\n .${this.cssPrefix}__source::before {\n content: '';\n display: inline-block;\n width: 4px;\n height: 4px;\n background: #666;\n border-radius: 50%;\n margin-right: 8px;\n vertical-align: middle;\n }\n\n .${this.cssPrefix}__status {\n padding: 4px 8px;\n background: #e8f5e9;\n color: #2d6a3e;\n border-radius: 4px;\n font-weight: 500;\n }\n\n /* Share button styling */\n .${this.cssPrefix}__footer button {\n background: none;\n border: none;\n color: #666;\n cursor: pointer;\n padding: 4px;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .${this.cssPrefix}__footer button:hover {\n color: #1a1a1a;\n }\n\n /* Responsive design */\n @media (max-width: 640px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n gap: 16px;\n }\n\n .${this.cssPrefix}__divider {\n height: 1px;\n width: 100%;\n }\n\n .${this.cssPrefix}__airport-code {\n font-size: 24px;\n }\n\n .${this.cssPrefix}__time-value {\n font-size: 20px;\n }\n\n .${this.cssPrefix}__footer {\n flex-direction: column;\n align-items: flex-start;\n }\n }\n `}}
|
|
2985
|
+
*/var Re=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())})};class Ae extends Oe{constructor(){super(...arguments),this.id="flight-card",this.name="Flight Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"flight",open:"[FLIGHT]",close:"[/FLIGHT]"}],this.cssPrefix="nr-flight-card"}renderHtmlBlockPlaceholder(t){if("flight"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`flight-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n style="min-width: 400px; max-width: 600px; margin: 16px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[FlightCardPlugin] Initialized")}afterReceive(t){return Re(this,void 0,void 0,function*(){try{const e=JSON.parse(t);if("flight"===e.type||this.isFlightData(e))return this.renderFlightCard(e)}catch(t){}const e=/\[FLIGHT\]([\s\S]*?)\[\/FLIGHT\]/g;let i,n=t;for(;null!==(i=e.exec(t));)try{const t=JSON.parse(i[1]),e=this.renderFlightCard(t);n=n.replace(i[0],e)}catch(t){console.warn("[FlightCardPlugin] Failed to parse flight data:",t)}return n})}renderHtmlBlock(t,e){if("flight"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderFlightCard(t)}catch(t){return console.warn("[FlightCardPlugin] renderHtmlBlock parse error:",t),""}}isFlightData(t){return t&&"object"==typeof t&&t.origin&&t.destination&&t.departureTime}renderFlightCard(t){const{origin:e,destination:i,departureTime:n,arrivalTime:o,departureDate:s,arrivalDate:r,terminal:a,gate:l,arrivalTerminal:d,arrivalGate:c,duration:h,flightNumber:u,airline:p,status:f,updated:m,source:g}=t;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-flight-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__route">\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(e)}</span>\n <div class="${this.cssPrefix}__flight-line">\n <svg class="${this.cssPrefix}__plane-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" fill="currentColor"/>\n </svg>\n ${h?`<span class="${this.cssPrefix}__duration">${this.escapeHtml(h)}</span>`:""}\n </div>\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(i)}</span>\n </div>\n ${u||p?`\n <div class="${this.cssPrefix}__flight-info">\n ${p?`<span class="${this.cssPrefix}__airline">${this.escapeHtml(p)}</span>`:""}\n ${u?`<span class="${this.cssPrefix}__flight-number">${this.escapeHtml(u)}</span>`:""}\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--departure">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(e)}</span>\n <span class="${this.cssPrefix}__date">${s?this.escapeHtml(s):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure de départ prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(n)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${a?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(a)}</span>\n </div>\n `:""}\n ${l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(l)}</span>\n </div>\n `:void 0===l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n\n <div class="${this.cssPrefix}__divider"></div>\n\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--arrival">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(i)}</span>\n <span class="${this.cssPrefix}__date">${r?this.escapeHtml(r):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure d'arrivée prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(o)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${d?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(d)}</span>\n </div>\n `:""}\n ${c?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(c)}</span>\n </div>\n `:void 0===c?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n </div>\n\n ${m||g||f?`\n <div class="${this.cssPrefix}__footer">\n ${m?`<span class="${this.cssPrefix}__updated">${this.escapeHtml(m)}</span>`:""}\n ${g?`<span class="${this.cssPrefix}__source">Source : ${this.escapeHtml(g)}</span>`:""}\n ${f?`<span class="${this.cssPrefix}__status">${this.escapeHtml(f)}</span>`:""}\n </div>\n `:""}\n </div>\n `}getCityName(t){return{JED:"Djeddah",TUN:"Tunis",CDG:"Paris",LHR:"London",JFK:"New York",DXB:"Dubai",LAX:"Los Angeles",ORD:"Chicago",ATL:"Atlanta",DFW:"Dallas",DEN:"Denver",SFO:"San Francisco",SEA:"Seattle",LAS:"Las Vegas",MCO:"Orlando",MIA:"Miami",IAH:"Houston",PHX:"Phoenix",BOS:"Boston",MSP:"Minneapolis",DTW:"Detroit",FLL:"Fort Lauderdale",PHL:"Philadelphia",LGA:"New York",BWI:"Baltimore",SLC:"Salt Lake City",SAN:"San Diego",DCA:"Washington",TPA:"Tampa",PDX:"Portland",STL:"St. Louis"}[t.toUpperCase()]||t}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 24px;\n margin: 16px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 600px;\n }\n\n .${this.cssPrefix}__header {\n margin-bottom: 24px;\n }\n\n .${this.cssPrefix}__route {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 16px;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__airport-code {\n font-size: 32px;\n font-weight: 700;\n color: #1a1a1a;\n letter-spacing: 0.5px;\n }\n\n .${this.cssPrefix}__flight-line {\n flex: 1;\n display: flex;\n align-items: center;\n justify-content: center;\n position: relative;\n padding: 0 16px;\n }\n\n .${this.cssPrefix}__flight-line::before {\n content: '';\n position: absolute;\n top: 50%;\n left: 0;\n right: 0;\n height: 2px;\n background: linear-gradient(to right, #e0e0e0 0%, #e0e0e0 100%);\n z-index: 0;\n }\n\n .${this.cssPrefix}__plane-icon {\n width: 24px;\n height: 24px;\n color: #666;\n background: white;\n padding: 4px;\n position: relative;\n z-index: 1;\n transform: rotate(90deg);\n }\n\n .${this.cssPrefix}__duration {\n position: absolute;\n top: -24px;\n background: white;\n padding: 2px 8px;\n font-size: 13px;\n color: #666;\n white-space: nowrap;\n }\n\n .${this.cssPrefix}__flight-info {\n display: flex;\n gap: 8px;\n align-items: center;\n font-size: 14px;\n color: #666;\n }\n\n .${this.cssPrefix}__airline {\n font-weight: 500;\n }\n\n .${this.cssPrefix}__flight-number {\n color: #999;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: 1fr auto 1fr;\n gap: 24px;\n }\n\n .${this.cssPrefix}__divider {\n width: 1px;\n background: #e0e0e0;\n }\n\n .${this.cssPrefix}__section {\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .${this.cssPrefix}__label {\n font-size: 12px;\n color: #999;\n text-transform: uppercase;\n letter-spacing: 0.5px;\n font-weight: 500;\n text-decoration: underline;\n }\n\n .${this.cssPrefix}__location {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__city {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__date {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__time-group {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__time-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__time-value {\n font-size: 24px;\n font-weight: 700;\n color: #2d6a3e;\n }\n\n .${this.cssPrefix}__terminal-gate {\n display: flex;\n gap: 16px;\n }\n\n .${this.cssPrefix}__info-item {\n display: flex;\n flex-direction: column;\n gap: 4px;\n }\n\n .${this.cssPrefix}__info-label {\n font-size: 11px;\n color: #999;\n }\n\n .${this.cssPrefix}__info-value {\n font-size: 18px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n margin-top: 16px;\n padding-top: 16px;\n border-top: 1px solid #e0e0e0;\n display: flex;\n justify-content: space-between;\n align-items: center;\n font-size: 12px;\n color: #666;\n gap: 12px;\n }\n\n .${this.cssPrefix}__updated {\n color: #999;\n }\n\n .${this.cssPrefix}__source {\n color: #666;\n }\n\n .${this.cssPrefix}__source::before {\n content: '';\n display: inline-block;\n width: 4px;\n height: 4px;\n background: #666;\n border-radius: 50%;\n margin-right: 8px;\n vertical-align: middle;\n }\n\n .${this.cssPrefix}__status {\n padding: 4px 8px;\n background: #e8f5e9;\n color: #2d6a3e;\n border-radius: 4px;\n font-weight: 500;\n }\n\n /* Share button styling */\n .${this.cssPrefix}__footer button {\n background: none;\n border: none;\n color: #666;\n cursor: pointer;\n padding: 4px;\n display: flex;\n align-items: center;\n gap: 4px;\n }\n\n .${this.cssPrefix}__footer button:hover {\n color: #1a1a1a;\n }\n\n /* Responsive design */\n @media (max-width: 640px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n gap: 16px;\n }\n\n .${this.cssPrefix}__divider {\n height: 1px;\n width: 100%;\n }\n\n .${this.cssPrefix}__airport-code {\n font-size: 24px;\n }\n\n .${this.cssPrefix}__time-value {\n font-size: 20px;\n }\n\n .${this.cssPrefix}__footer {\n flex-direction: column;\n align-items: flex-start;\n }\n }\n `}}
|
|
2912
2986
|
/**
|
|
2913
2987
|
* @license
|
|
2914
2988
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2915
2989
|
* SPDX-License-Identifier: MIT
|
|
2916
|
-
*/class Le extends ze{constructor(){super(...arguments),this.id="print-job-card",this.name="Print Job Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"printjob",open:"[PRINTJOB]",close:"[/PRINTJOB]"}],this.cssPrefix="nr-print-job-card"}renderHtmlBlockPlaceholder(t){if("printjob"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`printjob-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n avatar\n paragraph='{"rows":3}'\n style="min-width: 350px; max-width: 500px; margin: 8px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[PrintJobCardPlugin] Initialized")}renderHtmlBlock(t,e){if("printjob"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderPrintJobCard(t)}catch(t){return console.warn("[PrintJobCardPlugin] renderHtmlBlock parse error:",t),""}}renderPrintJobCard(t){const e=this.getStatusIcon(t.status),i=t.pagesPrinted&&t.totalPages?Math.round(t.pagesPrinted/t.totalPages*100):0;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-print-job-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__printer-icon">\n 🖨️\n </div>\n <div class="${this.cssPrefix}__header-content">\n <div class="${this.cssPrefix}__title">${this.escapeHtml(t.documentName)}</div>\n <div class="${this.cssPrefix}__subtitle">${this.escapeHtml(t.printerName)}</div>\n </div>\n <div class="${this.cssPrefix}__job-id">#${this.escapeHtml(t.jobId)}</div>\n </div>\n\n <div class="${this.cssPrefix}__status-row">\n <span class="${this.cssPrefix}__status-badge ${this.cssPrefix}__status-badge--${t.status}">\n ${e} ${this.formatStatus(t.status)}\n </span>\n ${t.priority&&"normal"!==t.priority?`\n <span class="${this.cssPrefix}__priority-badge ${this.cssPrefix}__priority-badge--${t.priority}">\n ${"high"===t.priority?"⚡":"🔽"} ${this.capitalize(t.priority)} Priority\n </span>\n `:""}\n </div>\n\n ${"printing"===t.status&&t.pagesPrinted&&t.totalPages?`\n <div class="${this.cssPrefix}__progress">\n <div class="${this.cssPrefix}__progress-bar">\n <div class="${this.cssPrefix}__progress-fill" style="width: ${i}%"></div>\n </div>\n <div class="${this.cssPrefix}__progress-text">\n ${t.pagesPrinted} / ${t.totalPages} pages (${i}%)\n </div>\n </div>\n `:""}\n\n ${"error"===t.status&&t.errorMessage?`\n <div class="${this.cssPrefix}__error-message">\n ⚠️ ${this.escapeHtml(t.errorMessage)}\n </div>\n `:""}\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Pages:</span>\n <span class="${this.cssPrefix}__detail-value">${t.totalPages}</span>\n </div>\n ${t.copies&&t.copies>1?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Copies:</span>\n <span class="${this.cssPrefix}__detail-value">${t.copies}</span>\n </div>\n `:""}\n ${t.colorMode?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Color Mode:</span>\n <span class="${this.cssPrefix}__detail-value">${this.capitalize(t.colorMode)}</span>\n </div>\n `:""}\n ${t.paperSize?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Paper Size:</span>\n <span class="${this.cssPrefix}__detail-value">${t.paperSize}</span>\n </div>\n `:""}\n ${t.userName?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">User:</span>\n <span class="${this.cssPrefix}__detail-value">${this.escapeHtml(t.userName)}</span>\n </div>\n `:""}\n ${t.estimatedTime&&"printing"===t.status?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Est. Time:</span>\n <span class="${this.cssPrefix}__detail-value">${t.estimatedTime}</span>\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__footer">\n <span class="${this.cssPrefix}__timestamp">\n 📅 Submitted: ${this.formatTimestamp(t.submittedAt)}\n </span>\n ${t.completedAt?`\n <span class="${this.cssPrefix}__timestamp">\n ✅ Completed: ${this.formatTimestamp(t.completedAt)}\n </span>\n `:""}\n </div>\n </div>\n `}getStatusColor(t){return{queued:"#ffa726",printing:"#42a5f5",completed:"#66bb6a",paused:"#ffb74d",error:"#ef5350",cancelled:"#78909c"}[t]||"#999"}getStatusIcon(t){return{queued:"⏳",printing:"🔄",completed:"✅",paused:"⏸️",error:"❌",cancelled:"🚫"}[t]||"📄"}formatStatus(t){return t.charAt(0).toUpperCase()+t.slice(1)}capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}formatTimestamp(t){try{return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(e){return t}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 20px;\n margin: 12px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 500px;\n border-left: 4px solid #42a5f5;\n }\n\n .${this.cssPrefix}__header {\n display: flex;\n align-items: flex-start;\n gap: 12px;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__printer-icon {\n font-size: 32px;\n line-height: 1;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__header-content {\n flex: 1;\n min-width: 0;\n }\n\n .${this.cssPrefix}__title {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n margin-bottom: 4px;\n word-break: break-word;\n }\n\n .${this.cssPrefix}__subtitle {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__job-id {\n font-size: 12px;\n color: #999;\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 4px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__status-row {\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__status-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__status-badge--queued {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--printing {\n background: #e3f2fd;\n color: #0d47a1;\n }\n\n .${this.cssPrefix}__status-badge--completed {\n background: #e8f5e9;\n color: #1b5e20;\n }\n\n .${this.cssPrefix}__status-badge--paused {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--error {\n background: #ffebee;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__status-badge--cancelled {\n background: #f5f5f5;\n color: #616161;\n }\n\n .${this.cssPrefix}__priority-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__priority-badge--high {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__priority-badge--low {\n background: #f5f5f5;\n color: #666;\n }\n\n .${this.cssPrefix}__progress {\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__progress-bar {\n width: 100%;\n height: 8px;\n background: #e0e0e0;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #42a5f5 0%, #1976d2 100%);\n transition: width 0.3s ease;\n border-radius: 4px;\n }\n\n .${this.cssPrefix}__progress-text {\n font-size: 13px;\n color: #666;\n text-align: center;\n }\n\n .${this.cssPrefix}__error-message {\n background: #ffebee;\n border-left: 3px solid #ef5350;\n padding: 12px;\n margin-bottom: 16px;\n border-radius: 4px;\n font-size: 13px;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 16px;\n padding: 16px;\n background: #f9f9f9;\n border-radius: 8px;\n }\n\n .${this.cssPrefix}__detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n }\n\n .${this.cssPrefix}__detail-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__detail-value {\n font-size: 13px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-top: 12px;\n border-top: 1px solid #e0e0e0;\n }\n\n .${this.cssPrefix}__timestamp {\n font-size: 11px;\n color: #999;\n }\n\n /* Responsive design */\n @media (max-width: 480px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n }\n\n .${this.cssPrefix}__header {\n flex-wrap: wrap;\n }\n\n .${this.cssPrefix}__job-id {\n order: -1;\n width: 100%;\n }\n }\n `}}
|
|
2990
|
+
*/class Le extends Oe{constructor(){super(...arguments),this.id="print-job-card",this.name="Print Job Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"printjob",open:"[PRINTJOB]",close:"[/PRINTJOB]"}],this.cssPrefix="nr-print-job-card"}renderHtmlBlockPlaceholder(t){if("printjob"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`printjob-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n avatar\n paragraph='{"rows":3}'\n style="min-width: 350px; max-width: 500px; margin: 8px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[PrintJobCardPlugin] Initialized")}renderHtmlBlock(t,e){if("printjob"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderPrintJobCard(t)}catch(t){return console.warn("[PrintJobCardPlugin] renderHtmlBlock parse error:",t),""}}renderPrintJobCard(t){const e=this.getStatusIcon(t.status),i=t.pagesPrinted&&t.totalPages?Math.round(t.pagesPrinted/t.totalPages*100):0;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-print-job-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__printer-icon">\n 🖨️\n </div>\n <div class="${this.cssPrefix}__header-content">\n <div class="${this.cssPrefix}__title">${this.escapeHtml(t.documentName)}</div>\n <div class="${this.cssPrefix}__subtitle">${this.escapeHtml(t.printerName)}</div>\n </div>\n <div class="${this.cssPrefix}__job-id">#${this.escapeHtml(t.jobId)}</div>\n </div>\n\n <div class="${this.cssPrefix}__status-row">\n <span class="${this.cssPrefix}__status-badge ${this.cssPrefix}__status-badge--${t.status}">\n ${e} ${this.formatStatus(t.status)}\n </span>\n ${t.priority&&"normal"!==t.priority?`\n <span class="${this.cssPrefix}__priority-badge ${this.cssPrefix}__priority-badge--${t.priority}">\n ${"high"===t.priority?"⚡":"🔽"} ${this.capitalize(t.priority)} Priority\n </span>\n `:""}\n </div>\n\n ${"printing"===t.status&&t.pagesPrinted&&t.totalPages?`\n <div class="${this.cssPrefix}__progress">\n <div class="${this.cssPrefix}__progress-bar">\n <div class="${this.cssPrefix}__progress-fill" style="width: ${i}%"></div>\n </div>\n <div class="${this.cssPrefix}__progress-text">\n ${t.pagesPrinted} / ${t.totalPages} pages (${i}%)\n </div>\n </div>\n `:""}\n\n ${"error"===t.status&&t.errorMessage?`\n <div class="${this.cssPrefix}__error-message">\n ⚠️ ${this.escapeHtml(t.errorMessage)}\n </div>\n `:""}\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Pages:</span>\n <span class="${this.cssPrefix}__detail-value">${t.totalPages}</span>\n </div>\n ${t.copies&&t.copies>1?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Copies:</span>\n <span class="${this.cssPrefix}__detail-value">${t.copies}</span>\n </div>\n `:""}\n ${t.colorMode?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Color Mode:</span>\n <span class="${this.cssPrefix}__detail-value">${this.capitalize(t.colorMode)}</span>\n </div>\n `:""}\n ${t.paperSize?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Paper Size:</span>\n <span class="${this.cssPrefix}__detail-value">${t.paperSize}</span>\n </div>\n `:""}\n ${t.userName?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">User:</span>\n <span class="${this.cssPrefix}__detail-value">${this.escapeHtml(t.userName)}</span>\n </div>\n `:""}\n ${t.estimatedTime&&"printing"===t.status?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Est. Time:</span>\n <span class="${this.cssPrefix}__detail-value">${t.estimatedTime}</span>\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__footer">\n <span class="${this.cssPrefix}__timestamp">\n 📅 Submitted: ${this.formatTimestamp(t.submittedAt)}\n </span>\n ${t.completedAt?`\n <span class="${this.cssPrefix}__timestamp">\n ✅ Completed: ${this.formatTimestamp(t.completedAt)}\n </span>\n `:""}\n </div>\n </div>\n `}getStatusColor(t){return{queued:"#ffa726",printing:"#42a5f5",completed:"#66bb6a",paused:"#ffb74d",error:"#ef5350",cancelled:"#78909c"}[t]||"#999"}getStatusIcon(t){return{queued:"⏳",printing:"🔄",completed:"✅",paused:"⏸️",error:"❌",cancelled:"🚫"}[t]||"📄"}formatStatus(t){return t.charAt(0).toUpperCase()+t.slice(1)}capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}formatTimestamp(t){try{return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(e){return t}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 20px;\n margin: 12px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 500px;\n border-left: 4px solid #42a5f5;\n }\n\n .${this.cssPrefix}__header {\n display: flex;\n align-items: flex-start;\n gap: 12px;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__printer-icon {\n font-size: 32px;\n line-height: 1;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__header-content {\n flex: 1;\n min-width: 0;\n }\n\n .${this.cssPrefix}__title {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n margin-bottom: 4px;\n word-break: break-word;\n }\n\n .${this.cssPrefix}__subtitle {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__job-id {\n font-size: 12px;\n color: #999;\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 4px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__status-row {\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__status-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__status-badge--queued {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--printing {\n background: #e3f2fd;\n color: #0d47a1;\n }\n\n .${this.cssPrefix}__status-badge--completed {\n background: #e8f5e9;\n color: #1b5e20;\n }\n\n .${this.cssPrefix}__status-badge--paused {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--error {\n background: #ffebee;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__status-badge--cancelled {\n background: #f5f5f5;\n color: #616161;\n }\n\n .${this.cssPrefix}__priority-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__priority-badge--high {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__priority-badge--low {\n background: #f5f5f5;\n color: #666;\n }\n\n .${this.cssPrefix}__progress {\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__progress-bar {\n width: 100%;\n height: 8px;\n background: #e0e0e0;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #42a5f5 0%, #1976d2 100%);\n transition: width 0.3s ease;\n border-radius: 4px;\n }\n\n .${this.cssPrefix}__progress-text {\n font-size: 13px;\n color: #666;\n text-align: center;\n }\n\n .${this.cssPrefix}__error-message {\n background: #ffebee;\n border-left: 3px solid #ef5350;\n padding: 12px;\n margin-bottom: 16px;\n border-radius: 4px;\n font-size: 13px;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 16px;\n padding: 16px;\n background: #f9f9f9;\n border-radius: 8px;\n }\n\n .${this.cssPrefix}__detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n }\n\n .${this.cssPrefix}__detail-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__detail-value {\n font-size: 13px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-top: 12px;\n border-top: 1px solid #e0e0e0;\n }\n\n .${this.cssPrefix}__timestamp {\n font-size: 11px;\n color: #999;\n }\n\n /* Responsive design */\n @media (max-width: 480px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n }\n\n .${this.cssPrefix}__header {\n flex-wrap: wrap;\n }\n\n .${this.cssPrefix}__job-id {\n order: -1;\n width: 100%;\n }\n }\n `}}
|
|
2917
2991
|
/**
|
|
2918
2992
|
* @license
|
|
2919
2993
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2920
2994
|
* SPDX-License-Identifier: MIT
|
|
2921
|
-
*/var Fe=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())})};class De extends
|
|
2995
|
+
*/var Fe=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())})};class De extends Oe{constructor(){super(...arguments),this.id="artifact",this.name="Artifact Plugin",this.version="1.0.0",this.artifacts=new Map}onInit(t){this.controller=t,t&&"function"==typeof t.on&&t.on("processing:end",()=>{var e,i;try{const n=[...(null===(e=t.getMessages)||void 0===e?void 0:e.call(t))||[]].reverse().find(t=>t.sender===q.Bot);n&&!(null===(i=n.metadata)||void 0===i?void 0:i.hasArtifacts)&&this.processMessage(n)}catch(t){}})}onMessageReceived(t){return Fe(this,void 0,void 0,function*(){t.sender===q.Bot&&this.processMessage(t)})}processMessage(t){var e;if(null===(e=t.metadata)||void 0===e?void 0:e.hasArtifacts)return void this.rebuildArtifactsFromMetadata(t);const i=t.text;if(!i)return;const n=/```(\w*)\n([\s\S]*?)```/g;let o;const s=[];let r=0;for(;null!==(o=n.exec(i));){const e=(o[1]||"text").toLowerCase(),i=o[2],n=`artifact-${t.id}-${r}`,a={id:n,language:e,content:i,title:this.extractTitle(i,e,r),messageId:t.id,index:r};s.push(a),this.artifacts.set(n,a),r++}if(0===s.length)return;let a=i,l=0;a=a.replaceAll(n,()=>`\0ARTIFACT_CARD_${s[l++].id}\0`),a=ct(a);for(const t of s)a=a.replace(`\0ARTIFACT_CARD_${t.id}\0`,this.renderPlaceholderCard(t));const d=this.getOncePerConversationStyleTag(this.getStyles());this.controller&&"function"==typeof this.controller.updateMessage&&this.controller.updateMessage(t.id,{text:d+a,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0,hasArtifacts:!0,artifactIds:s.map(t=>t.id),artifactOriginalText:i})})}rebuildArtifactsFromMetadata(t){var e,i;const n=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds;if(!(null==n?void 0:n.length))return;if(n.every(t=>this.artifacts.has(t)))return;const o=null===(i=t.metadata)||void 0===i?void 0:i.artifactOriginalText;if(!o)return;const s=/```(\w*)\n([\s\S]*?)```/g;let r,a=0;for(;null!==(r=s.exec(o));){const e=(r[1]||"text").toLowerCase(),i=r[2],n=`artifact-${t.id}-${a}`,o=this.extractTitle(i,e,a);this.artifacts.set(n,{id:n,language:e,content:i,title:o,messageId:t.id,index:a}),a++}}getArtifact(t){return this.artifacts.get(t)}getAllArtifacts(){return Array.from(this.artifacts.values())}getArtifactsForMessage(t){return Array.from(this.artifacts.values()).filter(e=>e.messageId===t)}processNow(t){var e;if(!this.controller||"function"!=typeof this.controller.getMessages)return!1;const i=(this.controller.getMessages()||[]).find(e=>e.id===t);return!(!i||i.sender!==q.Bot)&&((null===(e=i.metadata)||void 0===e?void 0:e.hasArtifacts)?(this.rebuildArtifactsFromMetadata(i),!0):(this.processMessage(i),!0))}extractTitle(t,e,i){const n=t.trimStart().split("\n")[0]||"",o=[/^\/\/\s*(.+)/,/^#\s*(.+)/,/^--\s*(.+)/,/^\/\*\s*(.*?)\*\//,/^<!--\s*(.*?)-->/];for(const t of o){const e=t.exec(n);if(null==e?void 0:e[1]){const t=e[1].trim();if(t.length>0&&t.length<=60)return t}}return`${dt(e)} Snippet ${i+1}`}renderPlaceholderCard(t){const e=dt(t.language),i=at(t.title);return`<div class="nr-artifact-card" data-artifact-id="${t.id}" role="button" tabindex="0" aria-label="View ${i}">\n <nr-icon name="code" size="small" class="nr-artifact-card__icon"></nr-icon>\n <span class="nr-artifact-card__info">\n <span class="nr-artifact-card__title">${i}</span>\n <nr-tag size="small" class="nr-artifact-card__lang">${e}</nr-tag>\n </span>\n <nr-icon name="chevron-right" size="small" class="nr-artifact-card__chevron"></nr-icon>\n</div>`}getStyles(){return"\n .nr-artifact-card {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 10px 14px;\n margin: 8px 0;\n background: #f6f8fa;\n border: 1px solid #d0d7de;\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s ease, border-color 0.15s ease;\n user-select: none;\n max-width: 100%;\n }\n .nr-artifact-card:hover {\n background: #eaeef2;\n border-color: #8b949e;\n }\n .nr-artifact-card:focus-visible {\n outline: 2px solid #0b5fff;\n outline-offset: 2px;\n }\n .nr-artifact-card__icon {\n flex-shrink: 0;\n color: #57606a;\n }\n .nr-artifact-card__info {\n display: flex;\n flex-direction: column;\n gap: 4px;\n min-width: 0;\n flex: 1;\n }\n .nr-artifact-card__title {\n font-size: 13px;\n font-weight: 500;\n color: #1f2937;\n white-space: nowrap;\n overflow: hidden;\n text-overflow: ellipsis;\n line-height: 1.3;\n }\n .nr-artifact-card__lang {\n align-self: flex-start;\n }\n .nr-artifact-card__chevron {\n flex-shrink: 0;\n color: #6c757d;\n }\n "}}
|
|
2922
2996
|
/**
|
|
2923
2997
|
* @license
|
|
2924
2998
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2925
2999
|
* SPDX-License-Identifier: MIT
|
|
2926
|
-
*/class Be extends
|
|
3000
|
+
*/class Be extends Oe{constructor(){super(...arguments),this.id="json-graph-renderer",this.name="JSON Graph Renderer",this.version="1.0.0"}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}if(null===e||"object"!=typeof e)return"";const i=Array.isArray(e)?e.map((t,e)=>this.renderNode(String(e),t)):Object.entries(e).map(([t,e])=>this.renderNode(t,e));return`\n <div style="padding:20px;font-family:system-ui,-apple-system,sans-serif;overflow:auto;">\n <div style="\n display:flex;align-items:center;gap:8px;\n margin-bottom:16px;padding-bottom:12px;\n border-bottom:1px solid #e2e8f0;\n ">\n <span style="\n display:inline-flex;align-items:center;justify-content:center;\n width:28px;height:28px;border-radius:6px;\n background:linear-gradient(135deg,#0ea5e9,#8b5cf6);\n color:#fff;font-size:14px;font-weight:700;\n ">{}</span>\n <span style="font-size:15px;font-weight:600;color:#1e293b;">\n JSON Graph View\n </span>\n <span style="\n margin-left:auto;font-size:12px;padding:2px 8px;border-radius:10px;\n background:#f1f5f9;color:#64748b;\n ">${Array.isArray(e)?e.length:Object.keys(e).length} root keys</span>\n </div>\n ${i.join("")}\n </div>\n `}renderNode(t,e,i=0){const n=null!==e&&"object"==typeof e&&!Array.isArray(e),o=Array.isArray(e),s=24*i;if(!n&&!o)return`\n <div style="display:flex;align-items:center;gap:8px;margin-left:${s}px;margin-bottom:6px;">\n <span style="\n display:inline-block;width:8px;height:8px;border-radius:50%;\n background:${this.typeColor(e)};flex-shrink:0;\n "></span>\n <span style="font-weight:600;font-size:13px;color:#334155;">\n ${at(t)}\n </span>\n <span style="\n font-size:13px;padding:2px 8px;border-radius:4px;\n background:${this.typeBg(e)};color:${this.typeColor(e)};\n border:1px solid ${this.typeColor(e)}20;\n ">${at(this.formatValue(e))}</span>\n </div>\n `;const r=o?e.map((t,e)=>[String(e),t]):Object.entries(e),a=o?`[ ${r.length} ]`:`{ ${r.length} }`,l=o?"#8b5cf6":"#0ea5e9";return`\n <div style="margin-left:${s}px;margin-bottom:4px;">\n <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">\n <span style="\n display:inline-flex;align-items:center;justify-content:center;\n width:20px;height:20px;border-radius:4px;\n background:${l}15;color:${l};font-size:11px;font-weight:700;\n border:1px solid ${l}30;\n ">${o?"[]":"{}"}</span>\n <span style="font-weight:600;font-size:13px;color:#334155;">\n ${at(t)}\n </span>\n <span style="\n font-size:11px;padding:1px 6px;border-radius:10px;\n background:${l}10;color:${l};font-weight:500;\n ">${a}</span>\n </div>\n <div style="margin-left:9px;padding-left:16px;border-left:2px solid #e2e8f0;">\n ${r.map(([t,e])=>this.renderNode(t,e,0)).join("")}\n </div>\n </div>\n `}typeColor(t){if(null===t)return"#94a3b8";switch(typeof t){case"string":return"#22c55e";case"number":return"#3b82f6";case"boolean":return"#f59e0b";default:return"#94a3b8"}}typeBg(t){if(null===t)return"#f1f5f9";switch(typeof t){case"string":return"#f0fdf4";case"number":return"#eff6ff";case"boolean":return"#fffbeb";default:return"#f1f5f9"}}formatValue(t){return null==t?"null":"string"==typeof t?`"${t}"`:"number"==typeof t||"boolean"==typeof t?String(t):JSON.stringify(t)}}
|
|
2927
3001
|
/**
|
|
2928
3002
|
* @license
|
|
2929
3003
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2930
3004
|
* SPDX-License-Identifier: MIT
|
|
2931
|
-
*/const Ne="nuraly:flow-diagram:split-width",Ue="nuraly:flow-diagram:panel-width",We="nr-flow-diagram-editor";class He extends HTMLElement{connectedCallback(){var t;const e=this.loadPanelWidth(),i=this.closestPanel();i&&(i.style.setProperty("width",`${e}px`),this._panelObserver=new ResizeObserver(()=>{const t=Math.round(i.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ue,String(t))}),this._panelObserver.observe(i));const n=this.attachShadow({mode:"open"}),o=null!==(t=this.getAttribute("content"))&&void 0!==t?t:"",s=this.unescapeHtml(o),r=this.prettyPrint(s);let a=null;try{a=JSON.parse(s)}catch(t){}n.innerHTML=`\n <style>${He.styles()}</style>\n ${this.renderHeader(a)}\n <div class="split">\n <div class="editor-pane">\n <textarea class="editor-textarea" spellcheck="false"></textarea>\n </div>\n <div class="resize-handle"><div class="resize-handle-bar"></div></div>\n <div class="diagram-pane">\n ${a?this.renderDiagram(a):'<div class="empty">Invalid JSON</div>'}\n </div>\n </div>\n <div class="error-bar" style="display:none;"></div>\n `;const l=n.querySelector(".editor-textarea");l&&(l.value=r);const d=localStorage.getItem(Ne);d&&requestAnimationFrame(()=>{const t=n.querySelector(".editor-pane");t&&(t.style.flex="none",t.style.width=`${d}px`)});const c=n.querySelector(".diagram-pane"),h=n.querySelector(".error-bar");l&&c&&h&&(l.addEventListener("input",()=>{try{const t=JSON.parse(l.value);if(t.Steps&&t.Transitions){c.innerHTML=this.renderDiagram(t);const e=n.querySelector(".header");if(e){const i=document.createElement("template");i.innerHTML=this.renderHeader(t).trim();const n=i.content.firstElementChild;n&&e.replaceWith(n)}}h.style.display="none"}catch(t){h.textContent=`Parse error: ${t.message}`,h.style.display="flex"}}),this.initResize(n))}disconnectedCallback(){var t,e;null===(t=this._panelObserver)||void 0===t||t.disconnect(),null===(e=this.closestPanel())||void 0===e||e.style.removeProperty("width")}loadPanelWidth(){const t=localStorage.getItem(Ue);return t?Math.max(300,Number.parseInt(t,10)):500}closestPanel(){var t,e,i,n;let o=null!==(e=null!==(t=this.parentElement)&&void 0!==t?t:this.getRootNode().host)&&void 0!==e?e:null;for(;o;){if(o instanceof HTMLElement&&o.classList.contains("artifact-panel"))return o;o=null!==(n=null!==(i=o.parentElement)&&void 0!==i?i:o.getRootNode().host)&&void 0!==n?n:null}return null}initResize(t){const e=t.querySelector(".split"),i=t.querySelector(".editor-pane"),n=t.querySelector(".resize-handle");if(!e||!i||!n)return;let o=!1,s=0,r=0;const a=t=>{if(!o)return;const n=t.clientX-s,a=e.getBoundingClientRect().width,l=Math.max(200,Math.min(r+n,a-200));i.style.flex="none",i.style.width=`${l}px`},l=()=>{if(!o)return;o=!1,n.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="";const t=Math.round(i.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ne,String(t)),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};n.addEventListener("mousedown",t=>{const e=t;e.preventDefault(),o=!0,s=e.clientX,r=i.getBoundingClientRect().width,n.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)})}prettyPrint(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch(e){return t}}unescapeHtml(t){const e=document.createElement("textarea");return e.innerHTML=t,e.value}renderHeader(t){var e,i;const n=null!==(e=null==t?void 0:t.Name)&&void 0!==e?e:"Workflow",o=(null!==(i=null==t?void 0:t.DocflowTags)&&void 0!==i?i:[]).map(t=>`<span class="tag">${at(t)}</span>`).join("");return`\n <div class="header">\n <span class="header-icon">⬡</span>\n <span class="header-name">${at(n)}</span>\n ${o}\n </div>\n `}renderDiagram(t){var e,i;const n=this.buildOrderedSteps(t),o=[];for(let t=0;t<n.length;t++){const s=n[t];o.push("event"===s.type?this.renderEventNode(s.name,null!==(e=s.eventType)&&void 0!==e?e:""):this.renderStepNode(s.name,null!==(i=s.step)&&void 0!==i?i:{})),t<n.length-1&&o.push(this.renderConnector())}return`<div class="diagram">${o.join("")}</div>`}buildOrderedSteps(t){var e,i,n,o;const s=[],r=null===(e=t.Events)||void 0===e?void 0:e.StartEvent,a=null===(i=t.Events)||void 0===i?void 0:i.EndEvent;r&&s.push({type:"event",name:r.Name||"Start",eventType:"start"});const l={};for(const e of Object.values(t.Transitions))l[e.Source]=e;let d=null!==(o=null===(n=l.StartEvent)||void 0===n?void 0:n.Target)&&void 0!==o?o:Object.keys(t.Steps)[0];const c=new Set;for(;d&&t.Steps[d]&&!c.has(d);){c.add(d),s.push({type:"step",name:d,step:t.Steps[d]});const e=l[d];if(!e||"EndEvent"===e.Target)break;d=e.Target}return a&&s.push({type:"event",name:a.Name||"End",eventType:"end"}),s}renderEventNode(t,e){const i="start"===e;return`\n <div class="node event-node ${i?"event-start":"event-end"}">\n <span class="event-icon">${i?"●":"■"}</span>\n <span class="event-label">${at(t)}</span>\n </div>\n `}renderStepNode(t,e){var i,n,o;const s=null!==(i=e.StepType)&&void 0!==i?i:"",r=null!==(o=null===(n=e.Description)||void 0===n?void 0:n.trim())&&void 0!==o?o:"",a=s?`<span class="step-badge ${"Worker"===s?"badge-worker":"badge-system"}">${at(s)}</span>`:"",l=r?`<div class="step-desc">${at(r)}</div>`:"";return`\n <div class="node step-node">\n <div class="step-header">\n <span class="step-name">${at(t)}</span>\n ${a}\n </div>\n ${l}\n </div>\n `}renderConnector(){return'\n <div class="connector">\n <div class="connector-line"></div>\n <div class="connector-arrow">▼</div>\n </div>\n '}static styles(){return"\n :host {\n display: flex;\n flex-direction: column;\n width: 100%;\n min-width: 480px;\n height: 100%;\n font-family: system-ui, -apple-system, sans-serif;\n color: #1e293b;\n overflow: hidden;\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 12px 16px;\n border-bottom: 1px solid #e2e8f0;\n background: #f8fafc;\n flex-shrink: 0;\n }\n .header-icon { font-size: 18px; color: #6366f1; }\n .header-name { font-weight: 600; font-size: 15px; }\n .tag {\n font-size: 11px;\n padding: 2px 8px;\n border-radius: 10px;\n background: #ede9fe;\n color: #6366f1;\n font-weight: 500;\n }\n\n .split {\n display: flex;\n flex: 1;\n min-height: 0;\n }\n\n .editor-pane {\n flex: 1;\n min-width: 200px;\n display: flex;\n overflow: hidden;\n }\n .editor-textarea {\n flex: 1;\n width: 100%;\n height: 100%;\n border: none;\n outline: none;\n resize: none;\n padding: 12px;\n font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;\n font-size: 12px;\n line-height: 1.6;\n color: #1e293b;\n background: #ffffff;\n box-sizing: border-box;\n tab-size: 2;\n }\n\n /* ── Resize handle ──────────────────────────────── */\n\n .resize-handle {\n flex-shrink: 0;\n width: 8px;\n cursor: col-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #f1f5f9;\n border-left: 1px solid #e2e8f0;\n border-right: 1px solid #e2e8f0;\n transition: background 0.15s;\n }\n .resize-handle:hover,\n .resize-handle.active { background: #e2e8f0; }\n .resize-handle-bar {\n width: 2px;\n height: 24px;\n border-radius: 1px;\n background: #cbd5e1;\n transition: background 0.15s;\n }\n .resize-handle:hover .resize-handle-bar,\n .resize-handle.active .resize-handle-bar { background: #94a3b8; }\n\n .diagram-pane {\n flex: 1;\n min-width: 200px;\n overflow-y: auto;\n padding: 24px;\n background: #f8fafc;\n }\n\n .diagram {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n color: #94a3b8;\n font-size: 14px;\n }\n\n /* ── Event nodes ──────────────────────────────────── */\n\n .event-node {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 20px;\n border-radius: 20px;\n font-size: 13px;\n font-weight: 600;\n }\n .event-start { background: #ecfdf5; border: 1.5px solid #86efac; color: #166534; }\n .event-start .event-icon { color: #22c55e; font-size: 10px; }\n .event-end { background: #fef2f2; border: 1.5px solid #fca5a5; color: #991b1b; }\n .event-end .event-icon { color: #ef4444; font-size: 10px; }\n\n /* ── Step nodes ───────────────────────────────────── */\n\n .step-node {\n width: 220px;\n padding: 12px 16px;\n border-radius: 8px;\n background: #ffffff;\n border: 1.5px solid #e2e8f0;\n box-shadow: 0 1px 3px rgba(0,0,0,0.06);\n }\n .step-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n }\n .step-name { font-weight: 600; font-size: 13px; color: #1e293b; }\n .step-badge {\n font-size: 10px;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.02em;\n flex-shrink: 0;\n }\n .badge-worker { background: #dbeafe; color: #1d4ed8; }\n .badge-system { background: #fef3c7; color: #92400e; }\n .step-desc { margin-top: 6px; font-size: 11px; color: #64748b; line-height: 1.4; }\n\n /* ── Connectors ───────────────────────────────────── */\n\n .connector {\n display: flex;\n flex-direction: column;\n align-items: center;\n height: 32px;\n }\n .connector-line { width: 2px; flex: 1; background: #cbd5e1; }\n .connector-arrow { font-size: 8px; color: #cbd5e1; line-height: 1; margin-top: -2px; }\n\n /* ── Error bar ────────────────────────────────────── */\n\n .error-bar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 8px 16px;\n background: #fef2f2;\n border-top: 1px solid #fecaca;\n color: #dc2626;\n font-size: 12px;\n flex-shrink: 0;\n }\n .error-bar::before { content: '⚠'; }\n "}}class Je extends ze{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(We)||customElements.define(We,He)}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}return null!==e&&"object"==typeof e&&e.Steps&&"object"==typeof e.Steps&&e.Transitions&&"object"==typeof e.Transitions?`<nr-flow-diagram-editor content="${at(t.content)}"></nr-flow-diagram-editor>`:""}}
|
|
3005
|
+
*/const Ne="nuraly:flow-diagram:split-width",Ue="nuraly:flow-diagram:panel-width",We="nr-flow-diagram-editor";class He extends HTMLElement{connectedCallback(){var t;const e=this.loadPanelWidth(),i=this.closestPanel();i&&(i.style.setProperty("width",`${e}px`),this._panelObserver=new ResizeObserver(()=>{const t=Math.round(i.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ue,String(t))}),this._panelObserver.observe(i));const n=this.attachShadow({mode:"open"}),o=null!==(t=this.getAttribute("content"))&&void 0!==t?t:"",s=this.unescapeHtml(o),r=this.prettyPrint(s);let a=null;try{a=JSON.parse(s)}catch(t){}n.innerHTML=`\n <style>${He.styles()}</style>\n ${this.renderHeader(a)}\n <div class="split">\n <div class="editor-pane">\n <textarea class="editor-textarea" spellcheck="false"></textarea>\n </div>\n <div class="resize-handle"><div class="resize-handle-bar"></div></div>\n <div class="diagram-pane">\n ${a?this.renderDiagram(a):'<div class="empty">Invalid JSON</div>'}\n </div>\n </div>\n <div class="error-bar" style="display:none;"></div>\n `;const l=n.querySelector(".editor-textarea");l&&(l.value=r);const d=localStorage.getItem(Ne);d&&requestAnimationFrame(()=>{const t=n.querySelector(".editor-pane");t&&(t.style.flex="none",t.style.width=`${d}px`)});const c=n.querySelector(".diagram-pane"),h=n.querySelector(".error-bar");l&&c&&h&&(l.addEventListener("input",()=>{try{const t=JSON.parse(l.value);if(t.Steps&&t.Transitions){c.innerHTML=this.renderDiagram(t);const e=n.querySelector(".header");if(e){const i=document.createElement("template");i.innerHTML=this.renderHeader(t).trim();const n=i.content.firstElementChild;n&&e.replaceWith(n)}}h.style.display="none"}catch(t){h.textContent=`Parse error: ${t.message}`,h.style.display="flex"}}),this.initResize(n))}disconnectedCallback(){var t,e;null===(t=this._panelObserver)||void 0===t||t.disconnect(),null===(e=this.closestPanel())||void 0===e||e.style.removeProperty("width")}loadPanelWidth(){const t=localStorage.getItem(Ue);return t?Math.max(300,Number.parseInt(t,10)):500}closestPanel(){var t,e,i,n;let o=null!==(e=null!==(t=this.parentElement)&&void 0!==t?t:this.getRootNode().host)&&void 0!==e?e:null;for(;o;){if(o instanceof HTMLElement&&o.classList.contains("artifact-panel"))return o;o=null!==(n=null!==(i=o.parentElement)&&void 0!==i?i:o.getRootNode().host)&&void 0!==n?n:null}return null}initResize(t){const e=t.querySelector(".split"),i=t.querySelector(".editor-pane"),n=t.querySelector(".resize-handle");if(!e||!i||!n)return;let o=!1,s=0,r=0;const a=t=>{if(!o)return;const n=t.clientX-s,a=e.getBoundingClientRect().width,l=Math.max(200,Math.min(r+n,a-200));i.style.flex="none",i.style.width=`${l}px`},l=()=>{if(!o)return;o=!1,n.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="";const t=Math.round(i.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ne,String(t)),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};n.addEventListener("mousedown",t=>{const e=t;e.preventDefault(),o=!0,s=e.clientX,r=i.getBoundingClientRect().width,n.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)})}prettyPrint(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch(e){return t}}unescapeHtml(t){const e=document.createElement("textarea");return e.innerHTML=t,e.value}renderHeader(t){var e,i;const n=null!==(e=null==t?void 0:t.Name)&&void 0!==e?e:"Workflow",o=(null!==(i=null==t?void 0:t.DocflowTags)&&void 0!==i?i:[]).map(t=>`<span class="tag">${at(t)}</span>`).join("");return`\n <div class="header">\n <span class="header-icon">⬡</span>\n <span class="header-name">${at(n)}</span>\n ${o}\n </div>\n `}renderDiagram(t){var e,i;const n=this.buildOrderedSteps(t),o=[];for(let t=0;t<n.length;t++){const s=n[t];o.push("event"===s.type?this.renderEventNode(s.name,null!==(e=s.eventType)&&void 0!==e?e:""):this.renderStepNode(s.name,null!==(i=s.step)&&void 0!==i?i:{})),t<n.length-1&&o.push(this.renderConnector())}return`<div class="diagram">${o.join("")}</div>`}buildOrderedSteps(t){var e,i,n,o;const s=[],r=null===(e=t.Events)||void 0===e?void 0:e.StartEvent,a=null===(i=t.Events)||void 0===i?void 0:i.EndEvent;r&&s.push({type:"event",name:r.Name||"Start",eventType:"start"});const l={};for(const e of Object.values(t.Transitions))l[e.Source]=e;let d=null!==(o=null===(n=l.StartEvent)||void 0===n?void 0:n.Target)&&void 0!==o?o:Object.keys(t.Steps)[0];const c=new Set;for(;d&&t.Steps[d]&&!c.has(d);){c.add(d),s.push({type:"step",name:d,step:t.Steps[d]});const e=l[d];if(!e||"EndEvent"===e.Target)break;d=e.Target}return a&&s.push({type:"event",name:a.Name||"End",eventType:"end"}),s}renderEventNode(t,e){const i="start"===e;return`\n <div class="node event-node ${i?"event-start":"event-end"}">\n <span class="event-icon">${i?"●":"■"}</span>\n <span class="event-label">${at(t)}</span>\n </div>\n `}renderStepNode(t,e){var i,n,o;const s=null!==(i=e.StepType)&&void 0!==i?i:"",r=null!==(o=null===(n=e.Description)||void 0===n?void 0:n.trim())&&void 0!==o?o:"",a=s?`<span class="step-badge ${"Worker"===s?"badge-worker":"badge-system"}">${at(s)}</span>`:"",l=r?`<div class="step-desc">${at(r)}</div>`:"";return`\n <div class="node step-node">\n <div class="step-header">\n <span class="step-name">${at(t)}</span>\n ${a}\n </div>\n ${l}\n </div>\n `}renderConnector(){return'\n <div class="connector">\n <div class="connector-line"></div>\n <div class="connector-arrow">▼</div>\n </div>\n '}static styles(){return"\n :host {\n display: flex;\n flex-direction: column;\n width: 100%;\n min-width: 480px;\n height: 100%;\n font-family: system-ui, -apple-system, sans-serif;\n color: #1e293b;\n overflow: hidden;\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 12px 16px;\n border-bottom: 1px solid #e2e8f0;\n background: #f8fafc;\n flex-shrink: 0;\n }\n .header-icon { font-size: 18px; color: #6366f1; }\n .header-name { font-weight: 600; font-size: 15px; }\n .tag {\n font-size: 11px;\n padding: 2px 8px;\n border-radius: 10px;\n background: #ede9fe;\n color: #6366f1;\n font-weight: 500;\n }\n\n .split {\n display: flex;\n flex: 1;\n min-height: 0;\n }\n\n .editor-pane {\n flex: 1;\n min-width: 200px;\n display: flex;\n overflow: hidden;\n }\n .editor-textarea {\n flex: 1;\n width: 100%;\n height: 100%;\n border: none;\n outline: none;\n resize: none;\n padding: 12px;\n font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;\n font-size: 12px;\n line-height: 1.6;\n color: #1e293b;\n background: #ffffff;\n box-sizing: border-box;\n tab-size: 2;\n }\n\n /* ── Resize handle ──────────────────────────────── */\n\n .resize-handle {\n flex-shrink: 0;\n width: 8px;\n cursor: col-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #f1f5f9;\n border-left: 1px solid #e2e8f0;\n border-right: 1px solid #e2e8f0;\n transition: background 0.15s;\n }\n .resize-handle:hover,\n .resize-handle.active { background: #e2e8f0; }\n .resize-handle-bar {\n width: 2px;\n height: 24px;\n border-radius: 1px;\n background: #cbd5e1;\n transition: background 0.15s;\n }\n .resize-handle:hover .resize-handle-bar,\n .resize-handle.active .resize-handle-bar { background: #94a3b8; }\n\n .diagram-pane {\n flex: 1;\n min-width: 200px;\n overflow-y: auto;\n padding: 24px;\n background: #f8fafc;\n }\n\n .diagram {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n color: #94a3b8;\n font-size: 14px;\n }\n\n /* ── Event nodes ──────────────────────────────────── */\n\n .event-node {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 20px;\n border-radius: 20px;\n font-size: 13px;\n font-weight: 600;\n }\n .event-start { background: #ecfdf5; border: 1.5px solid #86efac; color: #166534; }\n .event-start .event-icon { color: #22c55e; font-size: 10px; }\n .event-end { background: #fef2f2; border: 1.5px solid #fca5a5; color: #991b1b; }\n .event-end .event-icon { color: #ef4444; font-size: 10px; }\n\n /* ── Step nodes ───────────────────────────────────── */\n\n .step-node {\n width: 220px;\n padding: 12px 16px;\n border-radius: 8px;\n background: #ffffff;\n border: 1.5px solid #e2e8f0;\n box-shadow: 0 1px 3px rgba(0,0,0,0.06);\n }\n .step-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n }\n .step-name { font-weight: 600; font-size: 13px; color: #1e293b; }\n .step-badge {\n font-size: 10px;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.02em;\n flex-shrink: 0;\n }\n .badge-worker { background: #dbeafe; color: #1d4ed8; }\n .badge-system { background: #fef3c7; color: #92400e; }\n .step-desc { margin-top: 6px; font-size: 11px; color: #64748b; line-height: 1.4; }\n\n /* ── Connectors ───────────────────────────────────── */\n\n .connector {\n display: flex;\n flex-direction: column;\n align-items: center;\n height: 32px;\n }\n .connector-line { width: 2px; flex: 1; background: #cbd5e1; }\n .connector-arrow { font-size: 8px; color: #cbd5e1; line-height: 1; margin-top: -2px; }\n\n /* ── Error bar ────────────────────────────────────── */\n\n .error-bar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 8px 16px;\n background: #fef2f2;\n border-top: 1px solid #fecaca;\n color: #dc2626;\n font-size: 12px;\n flex-shrink: 0;\n }\n .error-bar::before { content: '⚠'; }\n "}}class Je extends Oe{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(We)||customElements.define(We,He)}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}return null!==e&&"object"==typeof e&&e.Steps&&"object"==typeof e.Steps&&e.Transitions&&"object"==typeof e.Transitions?`<nr-flow-diagram-editor content="${at(t.content)}"></nr-flow-diagram-editor>`:""}}
|
|
2932
3006
|
/**
|
|
2933
3007
|
* @license
|
|
2934
3008
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2935
3009
|
* SPDX-License-Identifier: MIT
|
|
2936
|
-
*/var qe=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())})};class Ve extends
|
|
3010
|
+
*/var qe=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())})};class Ve extends Oe{constructor(){super(...arguments),this.id="selection-card",this.name="Selection Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"selection",open:"[SELECTION]",close:"[/SELECTION]"}],this.cssPrefix="nr-selection-card"}renderHtmlBlockPlaceholder(t){if("selection"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`selection-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton\n active\n style="min-width: 300px; max-width: 500px; height: 80px; margin: 16px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[SelectionCardPlugin] Initialized")}afterReceive(t){return qe(this,void 0,void 0,function*(){try{const e=JSON.parse(t);if("selection"===e.type||this.isSelectionData(e))return this.renderSelectionCard(e)}catch(t){}const e=/\[SELECTION\]([\s\S]*?)\[\/SELECTION\]/g;let i,n=t;for(;null!==(i=e.exec(t));)try{const t=JSON.parse(i[1]),e=this.renderSelectionCard(t);n=n.replace(i[0],e)}catch(t){console.warn("[SelectionCardPlugin] Failed to parse selection data:",t)}return n})}renderHtmlBlock(t,e){if("selection"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderSelectionCard(t)}catch(t){return console.warn("[SelectionCardPlugin] renderHtmlBlock parse error:",t),""}}isSelectionData(t){return t&&"object"==typeof t&&Array.isArray(t.options)&&t.options.length>0&&t.options[0].label&&t.options[0].value}renderSelectionCard(t){const{title:e,options:i,columns:n=1}=t,o=this.getOncePerConversationStyleTag(this.getStyles()),s=i.map(t=>{const e=t.disabled?'aria-disabled="true"':"",i=t.disabled?`${this.cssPrefix}__option--disabled`:"",n=t.disabled?"-1":"0",o=t.disabled?"":`data-selection-value="${this.escapeHtml(t.value)}"`;return`\n <div class="${this.cssPrefix}__option ${i}"\n ${o}\n role="button"\n tabindex="${n}"\n ${e}>\n ${t.icon?`<nr-icon class="${this.cssPrefix}__option-icon" name="${this.escapeHtml(t.icon)}" size="small"></nr-icon>`:""}\n <div class="${this.cssPrefix}__option-content">\n <span class="${this.cssPrefix}__option-label">${this.escapeHtml(t.label)}</span>\n ${t.description?`<span class="${this.cssPrefix}__option-description">${this.escapeHtml(t.description)}</span>`:""}\n </div>\n </div>\n `}).join("");return`\n ${o}\n <div class="${this.cssPrefix}" data-nr-selection-card="true">\n ${e?`<div class="${this.cssPrefix}__title">${this.escapeHtml(e)}</div>`:""}\n <div class="${this.cssPrefix}__grid ${this.cssPrefix}__grid--cols-${n}">\n ${s}\n </div>\n </div>\n `}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n margin: 12px 0;\n max-width: 500px;\n font-family: system-ui, -apple-system, sans-serif;\n }\n\n .${this.cssPrefix}__title {\n font-size: 14px;\n font-weight: 600;\n color: #1a1a1a;\n margin-bottom: 10px;\n }\n\n .${this.cssPrefix}__grid {\n display: grid;\n gap: 8px;\n }\n\n .${this.cssPrefix}__grid--cols-1 {\n grid-template-columns: 1fr;\n }\n\n .${this.cssPrefix}__grid--cols-2 {\n grid-template-columns: 1fr 1fr;\n }\n\n .${this.cssPrefix}__grid--cols-3 {\n grid-template-columns: 1fr 1fr 1fr;\n }\n\n .${this.cssPrefix}__option {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 12px 16px;\n background: #ffffff;\n border: 1px solid #e0e0e0;\n border-radius: 10px;\n cursor: pointer;\n transition: all 0.15s ease;\n user-select: none;\n -webkit-user-select: none;\n }\n\n .${this.cssPrefix}__option:hover {\n border-color: #4f8cff;\n background: #f0f6ff;\n box-shadow: 0 1px 4px rgba(79, 140, 255, 0.12);\n }\n\n .${this.cssPrefix}__option:focus-visible {\n outline: 2px solid #4f8cff;\n outline-offset: 2px;\n }\n\n .${this.cssPrefix}__option:active:not([aria-disabled="true"]) {\n transform: scale(0.98);\n background: #dfeaff;\n }\n\n .${this.cssPrefix}__option--disabled {\n opacity: 0.5;\n cursor: not-allowed;\n pointer-events: none;\n }\n\n .${this.cssPrefix}__option-icon {\n flex-shrink: 0;\n color: #555;\n }\n\n .${this.cssPrefix}__option-content {\n display: flex;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n }\n\n .${this.cssPrefix}__option-label {\n font-size: 14px;\n font-weight: 500;\n color: #1a1a1a;\n line-height: 1.3;\n }\n\n .${this.cssPrefix}__option-description {\n font-size: 12px;\n color: #666;\n line-height: 1.3;\n }\n\n /* Responsive: force single column on mobile */\n @media (max-width: 480px) {\n .${this.cssPrefix}__grid--cols-2,\n .${this.cssPrefix}__grid--cols-3 {\n grid-template-columns: 1fr;\n }\n }\n `}}
|
|
2937
3011
|
/**
|
|
2938
3012
|
* @license
|
|
2939
3013
|
* Copyright 2023 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{
|
|
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};
|