@nuraly/lumenui 0.3.5 → 0.3.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nuralyui.bundle.js +2577 -1486
- package/dist/nuralyui.bundle.js.gz +0 -0
- package/dist/src/components/button/bundle.js +130 -39
- package/dist/src/components/button/bundle.js.gz +0 -0
- package/dist/src/components/button/button.component.js +7 -4
- package/dist/src/components/button/button.style.js +92 -2
- package/dist/src/components/canvas/base-canvas.component.d.ts +8 -0
- package/dist/src/components/canvas/base-canvas.component.js +75 -3
- package/dist/src/components/canvas/bundle.js +2540 -1201
- package/dist/src/components/canvas/bundle.js.gz +0 -0
- package/dist/src/components/canvas/controllers/collaboration.controller.d.ts +24 -11
- package/dist/src/components/canvas/controllers/collaboration.controller.js +176 -120
- package/dist/src/components/canvas/controllers/selection.controller.js +20 -0
- package/dist/src/components/canvas/interfaces/collaboration.interface.d.ts +8 -0
- package/dist/src/components/canvas/templates/index.d.ts +1 -0
- package/dist/src/components/canvas/templates/index.js +2 -0
- package/dist/src/components/canvas/templates/lock-overlay.template.d.ts +20 -0
- package/dist/src/components/canvas/templates/lock-overlay.template.js +33 -0
- package/dist/src/components/canvas/workflow-canvas.component.js +52 -24
- package/dist/src/components/canvas/workflow-canvas.style.js +62 -1
- package/dist/src/components/canvas/workflow-canvas.types.js +50 -4
- package/dist/src/components/chat-panel/bundle.js +10 -10
- package/dist/src/components/chat-panel/bundle.js.gz +0 -0
- package/dist/src/components/chat-panel/chat-panel.component.js +8 -8
- package/dist/src/components/chatbot/bundle.js +400 -242
- package/dist/src/components/chatbot/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/chatbot.style.js +156 -22
- package/dist/src/components/chatbot/chatbot.types.d.ts +1 -0
- package/dist/src/components/chatbot/core/chatbot-core.controller.js +13 -7
- package/dist/src/components/chatbot/plugins/artifact-plugin.js +0 -19
- package/dist/src/components/chatbot/plugins/flight-card-plugin.js +0 -35
- package/dist/src/components/chatbot/plugins/markdown-plugin.js +0 -4
- package/dist/src/components/chatbot/plugins/print-job-card-plugin.js +0 -36
- package/dist/src/components/chatbot/plugins/selection-card-plugin.js +0 -34
- package/dist/src/components/chatbot/providers/workflow-socket-provider.js +1 -2
- package/dist/src/components/chatbot/templates/input-box.template.js +58 -30
- package/dist/src/components/chatbot/templates/message.template.js +41 -31
- package/dist/src/components/chatbot/templates/thread-sidebar.template.js +38 -39
- package/dist/src/components/colorpicker/bundle.js +15 -10
- package/dist/src/components/colorpicker/bundle.js.gz +0 -0
- package/dist/src/components/colorpicker/color-picker.component.js +15 -10
- package/dist/src/components/datepicker/bundle.js +10 -10
- package/dist/src/components/datepicker/bundle.js.gz +0 -0
- package/dist/src/components/datepicker/datepicker.component.js +14 -22
- package/dist/src/components/dropdown/bundle.js +15 -14
- package/dist/src/components/dropdown/bundle.js.gz +0 -0
- package/dist/src/components/dropdown/dropdown.component.js +10 -9
- package/dist/src/components/dropdown/dropdown.style.js +2 -2
- package/dist/src/components/file-upload/bundle.js +15 -14
- package/dist/src/components/file-upload/bundle.js.gz +0 -0
- package/dist/src/components/file-upload/file-upload.component.js +15 -14
- package/dist/src/components/icon/bundle.js +7 -7
- package/dist/src/components/icon/bundle.js.gz +0 -0
- package/dist/src/components/icon/icon-paths.js +15 -0
- package/dist/src/components/iconpicker/bundle.js +216 -124
- package/dist/src/components/iconpicker/bundle.js.gz +0 -0
- package/dist/src/components/iconpicker/icon-picker.component.js +4 -4
- package/dist/src/components/menu/bundle.js +5 -2
- package/dist/src/components/menu/bundle.js.gz +0 -0
- package/dist/src/components/menu/menu.component.js +5 -2
- package/dist/src/components/modal/bundle.js +16 -13
- package/dist/src/components/modal/bundle.js.gz +0 -0
- package/dist/src/components/modal/modal.component.js +16 -13
- package/dist/src/components/panel/bundle.js +28 -28
- package/dist/src/components/panel/bundle.js.gz +0 -0
- package/dist/src/components/popconfirm/bundle.js +135 -41
- package/dist/src/components/popconfirm/bundle.js.gz +0 -0
- package/dist/src/components/popconfirm/popconfirm.component.d.ts +15 -119
- package/dist/src/components/popconfirm/popconfirm.component.js +158 -162
- package/dist/src/components/popconfirm/popconfirm.style.js +94 -0
- package/dist/src/components/presence/bundle.js +2 -1
- package/dist/src/components/presence/bundle.js.gz +0 -0
- package/dist/src/components/presence/presence.component.js +2 -1
- package/dist/src/components/table/bundle.js +3 -2
- package/dist/src/components/table/bundle.js.gz +0 -0
- package/dist/src/components/table/table.component.js +3 -2
- package/dist/src/components/tabs/bundle.js +3 -3
- package/dist/src/components/tabs/bundle.js.gz +0 -0
- package/dist/src/components/timepicker/bundle.js +3 -3
- package/dist/src/components/timepicker/bundle.js.gz +0 -0
- package/package.json +1 -1
- package/packages/common/dist/VERSIONS.md +1 -1
- package/packages/common/dist/shared/controllers/dropdown.controller.d.ts +4 -0
- package/packages/common/dist/shared/controllers/dropdown.controller.d.ts.map +1 -1
- package/packages/common/dist/shared/controllers/dropdown.controller.js +29 -3
- package/packages/common/dist/shared/controllers/dropdown.controller.js.map +1 -1
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{css as t,nothing as e,html as
|
|
1
|
+
import{css as t,nothing as e,html as i,LitElement as n}from"lit";import{property as o,state as s,customElement as r}from"lit/decorators.js";import{classMap as a}from"lit/directives/class-map.js";import{unsafeHTML as l}from"lit/directives/unsafe-html.js";import{repeat as d}from"lit/directives/repeat.js";import{styleMap as c}from"lit/directives/style-map.js";import{io as h}from"socket.io-client";
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2021 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
6
|
-
*/const u="lit-localize-status",p=(t,e,
|
|
6
|
+
*/const u="lit-localize-status",p=(t,e,i)=>{let n=t[0];for(let o=1;o<t.length;o++)n+=e[i?i[o-1]:o-1],n+=t[o];return n},f=t=>{return"string"!=typeof(e=t)&&"strTag"in e?p(t.strings,t.values):t;var e};
|
|
7
7
|
/**
|
|
8
8
|
* @license
|
|
9
9
|
* Copyright 2021 Google LLC
|
|
@@ -25,7 +25,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
25
25
|
* @license
|
|
26
26
|
* Copyright 2014 Travis Webb
|
|
27
27
|
* SPDX-License-Identifier: MIT
|
|
28
|
-
*/const x=[];for(let t=0;t<256;t++)x[t]=(t>>4&15).toString(16)+(15&t).toString(16);function w(t,e){return(e?"h":"s")+function(t){let e=0,
|
|
28
|
+
*/const x=[];for(let t=0;t<256;t++)x[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 x[l>>8]+x[255&l]+x[r>>8]+x[255&r]+x[o>>8]+x[255&o]+x[i>>8]+x[255&i]}
|
|
29
29
|
/**
|
|
30
30
|
* @license
|
|
31
31
|
* Copyright 2020 Google LLC
|
|
@@ -35,12 +35,12 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
35
35
|
* @license
|
|
36
36
|
* Copyright 2021 Google LLC
|
|
37
37
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
38
|
-
*/const _=new WeakMap,$=new Map;function k(t,e,
|
|
38
|
+
*/const _=new WeakMap,$=new Map;function k(t,e,i){if(t){const n=i?.id??function(t){const e="string"==typeof t?t:t.strings;let i=$.get(e);void 0===i&&(i=w(e,"string"!=typeof t&&!("strTag"in t)),$.set(e,i));return i}
|
|
39
39
|
/**
|
|
40
40
|
* @license
|
|
41
41
|
* Copyright 2021 Google LLC
|
|
42
42
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
43
|
-
*/(e),o=t[
|
|
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 y;O.resolve();let I=0;const R=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:A,setLocale:j}),A=()=>z,j=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 y),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 F=t`
|
|
44
44
|
:host {
|
|
45
45
|
display: block;
|
|
46
46
|
width: 100%;
|
|
@@ -300,14 +300,13 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
300
300
|
}
|
|
301
301
|
|
|
302
302
|
.thread-item--active {
|
|
303
|
-
background-color: #
|
|
304
|
-
color: #
|
|
305
|
-
border-color:
|
|
303
|
+
background-color: #ededed;
|
|
304
|
+
color: #161616;
|
|
305
|
+
border-color: transparent;
|
|
306
306
|
}
|
|
307
307
|
|
|
308
308
|
.thread-item--active:hover {
|
|
309
|
-
background-color: #
|
|
310
|
-
opacity: 0.95;
|
|
309
|
+
background-color: #e5e5e5;
|
|
311
310
|
}
|
|
312
311
|
|
|
313
312
|
.thread-item__header {
|
|
@@ -333,14 +332,18 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
333
332
|
align-items: center;
|
|
334
333
|
gap: 2px;
|
|
335
334
|
flex-shrink: 0;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
.thread-item__actions .thread-item__menu {
|
|
336
338
|
opacity: 0;
|
|
337
339
|
pointer-events: none;
|
|
338
340
|
transition: opacity 0.15s ease;
|
|
339
341
|
}
|
|
340
342
|
|
|
341
|
-
.thread-item:hover .thread-
|
|
342
|
-
.thread-item--active .thread-
|
|
343
|
-
.thread-item:focus-within .thread-
|
|
343
|
+
.thread-item:hover .thread-item__menu,
|
|
344
|
+
.thread-item--active .thread-item__menu,
|
|
345
|
+
.thread-item:focus-within .thread-item__menu,
|
|
346
|
+
.thread-item__actions nr-dropdown[open] .thread-item__menu {
|
|
344
347
|
opacity: 1;
|
|
345
348
|
pointer-events: auto;
|
|
346
349
|
}
|
|
@@ -370,27 +373,23 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
370
373
|
background-color: rgba(59, 130, 246, 0.1);
|
|
371
374
|
}
|
|
372
375
|
|
|
373
|
-
.thread-item__actions nr-popconfirm {
|
|
374
|
-
margin-top: 4px;
|
|
375
|
-
}
|
|
376
|
-
|
|
377
376
|
.thread-item__delete:hover {
|
|
378
377
|
color: #ef4444;
|
|
379
378
|
background-color: rgba(239, 68, 68, 0.1);
|
|
380
379
|
}
|
|
381
380
|
|
|
382
381
|
.thread-item--active .thread-item__action-btn {
|
|
383
|
-
color: rgba(
|
|
382
|
+
color: rgba(22, 22, 22, 0.6);
|
|
384
383
|
}
|
|
385
384
|
|
|
386
385
|
.thread-item--active .thread-item__action-btn:hover {
|
|
387
|
-
color: #
|
|
388
|
-
background-color: rgba(
|
|
386
|
+
color: #161616;
|
|
387
|
+
background-color: rgba(0, 0, 0, 0.06);
|
|
389
388
|
}
|
|
390
389
|
|
|
391
390
|
.thread-item--active .thread-item__delete:hover {
|
|
392
391
|
color: #ef4444;
|
|
393
|
-
background-color: rgba(239, 68, 68, 0.
|
|
392
|
+
background-color: rgba(239, 68, 68, 0.1);
|
|
394
393
|
}
|
|
395
394
|
|
|
396
395
|
.thread-item__bookmark--active {
|
|
@@ -423,7 +422,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
423
422
|
}
|
|
424
423
|
|
|
425
424
|
.thread-item--active .thread-item__rename-input {
|
|
426
|
-
background:
|
|
425
|
+
background: #ffffff;
|
|
427
426
|
}
|
|
428
427
|
|
|
429
428
|
.thread-item__preview {
|
|
@@ -462,11 +461,13 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
462
461
|
.messages {
|
|
463
462
|
flex: 1;
|
|
464
463
|
overflow-y: auto;
|
|
464
|
+
overflow-x: hidden;
|
|
465
465
|
display: flex;
|
|
466
466
|
flex-direction: column;
|
|
467
467
|
gap: 0;
|
|
468
468
|
background-color: #ffffff;
|
|
469
|
-
padding: 8px
|
|
469
|
+
padding: 8px 1rem;
|
|
470
|
+
box-sizing: border-box;
|
|
470
471
|
justify-content: flex-start; /* Always align messages to top */
|
|
471
472
|
}
|
|
472
473
|
|
|
@@ -526,16 +527,22 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
526
527
|
border: 0 solid transparent;
|
|
527
528
|
}
|
|
528
529
|
|
|
529
|
-
/* Message attachments (file
|
|
530
|
+
/* Message attachments (file thumbs) */
|
|
530
531
|
.message__attachments {
|
|
531
532
|
display: flex;
|
|
532
533
|
flex-wrap: wrap;
|
|
533
|
-
gap: 0.
|
|
534
|
-
margin-top: 0.
|
|
534
|
+
gap: 0.375rem;
|
|
535
|
+
margin-top: 0.375rem;
|
|
535
536
|
position: relative;
|
|
536
537
|
z-index: 1;
|
|
537
538
|
}
|
|
538
539
|
|
|
540
|
+
.file-thumb--message {
|
|
541
|
+
width: 48px;
|
|
542
|
+
height: 48px;
|
|
543
|
+
border-radius: 8px;
|
|
544
|
+
}
|
|
545
|
+
|
|
539
546
|
.message-file-preview-dropdown {
|
|
540
547
|
display: inline-block;
|
|
541
548
|
position: relative;
|
|
@@ -1033,6 +1040,134 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1033
1040
|
cursor: help;
|
|
1034
1041
|
}
|
|
1035
1042
|
|
|
1043
|
+
/* Claude-style upload thumbnail chip */
|
|
1044
|
+
.file-thumb {
|
|
1045
|
+
position: relative;
|
|
1046
|
+
display: inline-flex;
|
|
1047
|
+
align-items: center;
|
|
1048
|
+
justify-content: center;
|
|
1049
|
+
width: 56px;
|
|
1050
|
+
height: 56px;
|
|
1051
|
+
border-radius: 10px;
|
|
1052
|
+
overflow: hidden;
|
|
1053
|
+
background-color: #f3f4f6;
|
|
1054
|
+
border: 1px solid #e5e7eb;
|
|
1055
|
+
cursor: pointer;
|
|
1056
|
+
outline: none;
|
|
1057
|
+
transition: border-color 0.15s ease, box-shadow 0.15s ease;
|
|
1058
|
+
flex-shrink: 0;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
.file-thumb:hover,
|
|
1062
|
+
.file-thumb:focus-visible {
|
|
1063
|
+
border-color: #7c3aed;
|
|
1064
|
+
box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.15);
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
.file-thumb__image {
|
|
1068
|
+
width: 100%;
|
|
1069
|
+
height: 100%;
|
|
1070
|
+
object-fit: cover;
|
|
1071
|
+
display: block;
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
.file-thumb__ext {
|
|
1075
|
+
width: 100%;
|
|
1076
|
+
height: 100%;
|
|
1077
|
+
display: flex;
|
|
1078
|
+
align-items: center;
|
|
1079
|
+
justify-content: center;
|
|
1080
|
+
background: linear-gradient(135deg, #ede9fe, #ddd6fe);
|
|
1081
|
+
color: #5b21b6;
|
|
1082
|
+
font-weight: 600;
|
|
1083
|
+
font-size: 0.7rem;
|
|
1084
|
+
letter-spacing: 0.04em;
|
|
1085
|
+
text-transform: uppercase;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
.file-thumb__ext-label {
|
|
1089
|
+
padding: 0 4px;
|
|
1090
|
+
max-width: 100%;
|
|
1091
|
+
overflow: hidden;
|
|
1092
|
+
text-overflow: ellipsis;
|
|
1093
|
+
white-space: nowrap;
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
.file-thumb__spinner {
|
|
1097
|
+
position: absolute;
|
|
1098
|
+
inset: 0;
|
|
1099
|
+
display: flex;
|
|
1100
|
+
align-items: center;
|
|
1101
|
+
justify-content: center;
|
|
1102
|
+
background-color: rgba(255, 255, 255, 0.55);
|
|
1103
|
+
backdrop-filter: blur(1px);
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
.file-thumb__spinner-ring {
|
|
1107
|
+
width: 20px;
|
|
1108
|
+
height: 20px;
|
|
1109
|
+
border-radius: 50%;
|
|
1110
|
+
border: 2px solid rgba(124, 58, 237, 0.25);
|
|
1111
|
+
border-top-color: #7c3aed;
|
|
1112
|
+
animation: file-thumb-spin 0.8s linear infinite;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
.file-thumb--uploading {
|
|
1116
|
+
pointer-events: none;
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
.file-thumb--uploading .file-thumb__remove {
|
|
1120
|
+
display: none;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
@keyframes file-thumb-spin {
|
|
1124
|
+
to { transform: rotate(360deg); }
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
.file-thumb__remove {
|
|
1128
|
+
position: absolute;
|
|
1129
|
+
top: 2px;
|
|
1130
|
+
right: 2px;
|
|
1131
|
+
width: 16px;
|
|
1132
|
+
height: 16px;
|
|
1133
|
+
padding: 0;
|
|
1134
|
+
border: none;
|
|
1135
|
+
border-radius: 50%;
|
|
1136
|
+
background-color: rgba(17, 24, 39, 0.7);
|
|
1137
|
+
color: #ffffff;
|
|
1138
|
+
display: inline-flex;
|
|
1139
|
+
align-items: center;
|
|
1140
|
+
justify-content: center;
|
|
1141
|
+
cursor: pointer;
|
|
1142
|
+
opacity: 0;
|
|
1143
|
+
transition: opacity 0.15s ease, background-color 0.15s ease;
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
.file-thumb:hover .file-thumb__remove,
|
|
1147
|
+
.file-thumb:focus-within .file-thumb__remove {
|
|
1148
|
+
opacity: 1;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
.file-thumb__remove:hover {
|
|
1152
|
+
background-color: rgba(17, 24, 39, 0.9);
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/* Dropdown preview extension tile (non-image files) */
|
|
1156
|
+
.file-preview-ext {
|
|
1157
|
+
width: 72px;
|
|
1158
|
+
height: 72px;
|
|
1159
|
+
display: flex;
|
|
1160
|
+
align-items: center;
|
|
1161
|
+
justify-content: center;
|
|
1162
|
+
border-radius: 10px;
|
|
1163
|
+
background: linear-gradient(135deg, #ede9fe, #ddd6fe);
|
|
1164
|
+
color: #5b21b6;
|
|
1165
|
+
font-weight: 600;
|
|
1166
|
+
font-size: 0.875rem;
|
|
1167
|
+
letter-spacing: 0.04em;
|
|
1168
|
+
text-transform: uppercase;
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1036
1171
|
/* File preview dropdown content */
|
|
1037
1172
|
.file-preview-content {
|
|
1038
1173
|
display: flex;
|
|
@@ -1544,7 +1679,6 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1544
1679
|
justify-content: center;
|
|
1545
1680
|
background: #e0e0e0;
|
|
1546
1681
|
transition: background 0.15s;
|
|
1547
|
-
z-index: 1;
|
|
1548
1682
|
}
|
|
1549
1683
|
.artifact-panel__resize-handle:hover,
|
|
1550
1684
|
.artifact-panel__resize-handle--active {
|
|
@@ -1827,7 +1961,7 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1827
1961
|
* @license
|
|
1828
1962
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1829
1963
|
* SPDX-License-Identifier: MIT
|
|
1830
|
-
*/;const
|
|
1964
|
+
*/;const D=t=>class extends t{constructor(){super(...arguments),this.handleSystemThemeChange=()=>{this.closest("[data-theme]")||document.documentElement.hasAttribute("data-theme")||this.requestUpdate()}}connectedCallback(){super.connectedCallback(),this.setupThemeObserver(),this.setupDesignSystemObserver(),this.setupSystemThemeListener()}disconnectedCallback(){var t,e,i;super.disconnectedCallback(),null===(t=this.themeObserver)||void 0===t||t.disconnect(),null===(e=this.designSystemObserver)||void 0===e||e.disconnect(),null===(i=this.mediaQuery)||void 0===i||i.removeEventListener("change",this.handleSystemThemeChange)}get currentTheme(){var t,e;const i=(null===(t=this.closest("[data-theme]"))||void 0===t?void 0:t.getAttribute("data-theme"))||document.documentElement.getAttribute("data-theme");return i||((null===(e=window.matchMedia)||void 0===e?void 0:e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light")}get currentDesignSystem(){var t;const e=(null===(t=this.closest("[design-system]"))||void 0===t?void 0:t.getAttribute("design-system"))||document.documentElement.getAttribute("design-system");return"carbon"===e?e:"default"}setupThemeObserver(){this.themeObserver=new MutationObserver(()=>{this.requestUpdate()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}setupDesignSystemObserver(){this.designSystemObserver=new MutationObserver(()=>{this.requestUpdate()}),this.designSystemObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["design-system"]})}setupSystemThemeListener(){window.matchMedia&&(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.mediaQuery.addEventListener("change",this.handleSystemThemeChange))}},N=()=>{var t;return void 0!==globalThis.litElementVersions||"undefined"!=typeof process&&"development"===(null===(t=process.env)||void 0===t?void 0:t.NODE_ENV)||"undefined"!=typeof window&&("localhost"===window.location.hostname||"127.0.0.1"===window.location.hostname)},L=t=>class extends t{constructor(){super(...arguments),this.requiredComponents=[]}validateDependencies(){if(N())for(const t of this.requiredComponents)if(!this.isComponentAvailable(t))throw new Error(`Required component "${t}" is not registered. Please import and register the component before using ${this.tagName.toLowerCase()}. Example: import '@nuralyui/${t}';`)}validateDependenciesWithHandler(t){if(!N())return!0;let e=!0;for(const i of this.requiredComponents)if(!this.isComponentAvailable(i)){e=!1;const n=new Error(`Required component "${i}" is not registered. Please import and register the component before using ${this.tagName.toLowerCase()}.`);t?t(i,n):console.error(n.message)}return e}isComponentAvailable(t){return!!customElements.get(t)}getMissingDependencies(){return this.requiredComponents.filter(t=>!this.isComponentAvailable(t))}areDependenciesAvailable(){return this.requiredComponents.every(t=>this.isComponentAvailable(t))}addRequiredComponent(t){this.requiredComponents.includes(t)||this.requiredComponents.push(t)}removeRequiredComponent(t){const e=this.requiredComponents.indexOf(t);e>-1&&this.requiredComponents.splice(e,1)}},B=t=>class extends t{dispatchCustomEvent(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchEventWithMetadata(t,e){var i;const n=Object.assign(Object.assign({},e),{timestamp:Date.now(),componentName:(null===(i=this.tagName)||void 0===i?void 0:i.toLowerCase())||"unknown"});this.dispatchCustomEvent(t,n)}dispatchInputEvent(t,e){const i=Object.assign({target:e.target||this,value:e.value,originalEvent:e.originalEvent},e);this.dispatchCustomEvent(t,i)}dispatchFocusEvent(t,e){const i=Object.assign({target:e.target||this,value:e.value,focused:e.focused,cursorPosition:e.cursorPosition,selectedText:e.selectedText},e);this.dispatchCustomEvent(t,i)}dispatchValidationEvent(t,e){var i;const n=Object.assign({target:e.target||this,value:e.value,isValid:null!==(i=e.isValid)&&void 0!==i&&i,error:e.error},e);this.dispatchCustomEvent(t,n)}dispatchActionEvent(t,e){const i=Object.assign({target:e.target||this,action:e.action,previousValue:e.previousValue,newValue:e.newValue},e);this.dispatchCustomEvent(t,i)}isReadonlyKeyAllowed(t){if(t.ctrlKey||t.metaKey){return["KeyA","KeyC"].includes(t.code)}return["Tab","Escape","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"].includes(t.key)}isActivationKey(t){return"Enter"===t.key||" "===t.key}},U=new Set,W=new Map;
|
|
1831
1965
|
/**
|
|
1832
1966
|
* @license
|
|
1833
1967
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
@@ -1838,23 +1972,23 @@ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1838
1972
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1839
1973
|
* SPDX-License-Identifier: MIT
|
|
1840
1974
|
*/
|
|
1841
|
-
const H=t=>{class e extends t{constructor(){super(...arguments),this.o=null}createRenderRoot(){return this.constructor.useShadowDom?super.createRenderRoot():this}connectedCallback(){const t=this.constructor.useShadowDom;if(!t&&null===this.o)for(this.o=[];this.firstChild;)this.o.push(this.removeChild(this.firstChild));if(super.connectedCallback(),!t){const t=this.constructor,e=this.tagName.toLowerCase(),
|
|
1975
|
+
const H=t=>{class e extends t{constructor(){super(...arguments),this.o=null}createRenderRoot(){return this.constructor.useShadowDom?super.createRenderRoot():this}connectedCallback(){const t=this.constructor.useShadowDom;if(!t&&null===this.o)for(this.o=[];this.firstChild;)this.o.push(this.removeChild(this.firstChild));if(super.connectedCallback(),!t){const t=this.constructor,e=this.tagName.toLowerCase(),i=t.styles;if(i){const t=J(i);t&&function(t,e,i){var n;if(!W.has(t)){const i=new CSSStyleSheet;i.replaceSync(e),W.set(t,i)}const o=W.get(t),s=`doc:${t}`;if(U.has(s)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,o],U.add(s)),i){let e=i;for(;e;){const i=e.getRootNode();if(!(i instanceof ShadowRoot))break;{const s=`shadow:${((null===(n=i.host)||void 0===n?void 0:n.tagName)||"").toLowerCase()}:${t}`;U.has(s)||(i.adoptedStyleSheets=[...i.adoptedStyleSheets,o],U.add(s)),e=i.host}}}}(e,t,this)}}}get lightChildren(){return this.o?this.o.filter(t=>!(t instanceof Element&&t.hasAttribute("slot"))):[]}lightChildrenNamed(t){return this.o?this.o.filter(e=>e instanceof Element&&e.getAttribute("slot")===t):[]}}return e.useShadowDom=!1,e};function J(t){return Array.isArray(t)?t.map(t=>J(t)).filter(Boolean).join("\n"):t&&"string"==typeof t.cssText?t.cssText:"string"==typeof t?t:""}
|
|
1842
1976
|
/**
|
|
1843
1977
|
* @license
|
|
1844
1978
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1845
1979
|
* SPDX-License-Identifier: MIT
|
|
1846
|
-
*/var q,V,G,K,Y,X,Q;!function(t){t.User="user",t.Bot="bot",t.System="system"}(q||(q={})),function(t){t.Dots="dots",t.Spinner="spinner",t.Wave="wave",t.Typing="typing"}(V||(V={})),function(t){t.Small="small",t.Medium="medium",t.Large="large",t.Full="full"}(G||(G={})),function(t){t.Default="default",t.Minimal="minimal",t.Rounded="rounded",t.ChatGPT="chatgpt"}(K||(K={})),function(t){t.Default="default",t.Error="error",t.Success="success",t.Loading="loading",t.Pending="pending"}(Y||(Y={})),function(t){t.Image="image",t.Document="document",t.Audio="audio",t.Video="video",t.Archive="archive",t.Code="code",t.Unknown="unknown"}(X||(X={})),function(t){t.Upload="upload",t.Clear="clear",t.Export="export",t.Settings="settings",t.Microphone="microphone",t.Camera="camera",t.Attach="attach"}(Q||(Q={}));const Z="",tt=1e3,et=100,
|
|
1980
|
+
*/var q,V,G,K,Y,X,Q;!function(t){t.User="user",t.Bot="bot",t.System="system"}(q||(q={})),function(t){t.Dots="dots",t.Spinner="spinner",t.Wave="wave",t.Typing="typing"}(V||(V={})),function(t){t.Small="small",t.Medium="medium",t.Large="large",t.Full="full"}(G||(G={})),function(t){t.Default="default",t.Minimal="minimal",t.Rounded="rounded",t.ChatGPT="chatgpt"}(K||(K={})),function(t){t.Default="default",t.Error="error",t.Success="success",t.Loading="loading",t.Pending="pending"}(Y||(Y={})),function(t){t.Image="image",t.Document="document",t.Audio="audio",t.Video="video",t.Archive="archive",t.Code="code",t.Unknown="unknown"}(X||(X={})),function(t){t.Upload="upload",t.Clear="clear",t.Export="export",t.Settings="settings",t.Microphone="microphone",t.Camera="camera",t.Attach="attach"}(Q||(Q={}));const Z="",tt=1e3,et=100,it=10485760,nt=5,ot=["image/jpeg","image/png","image/gif","image/webp","application/pdf","text/plain","text/csv","application/json","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],st={"image/":X.Image,"audio/":X.Audio,"video/":X.Video,"application/pdf":X.Document,"application/msword":X.Document,"application/vnd.openxmlformats-officedocument":X.Document,"text/":X.Document,"application/zip":X.Archive,"application/x-rar":X.Archive,"application/javascript":X.Code,"text/html":X.Code,"text/css":X.Code};
|
|
1847
1981
|
/**
|
|
1848
1982
|
* @license
|
|
1849
1983
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1850
1984
|
* SPDX-License-Identifier: MIT
|
|
1851
1985
|
*/
|
|
1852
|
-
function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";const
|
|
1986
|
+
function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";const i=new Date,n={hour:"numeric",minute:"2-digit",hour12:!0};if(e.toDateString()===i.toDateString())return e.toLocaleTimeString(void 0,n);const o=Object.assign({month:"short",day:"numeric"},n);return e.toLocaleDateString(void 0,o)}function at(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}const lt={javascript:"JavaScript",typescript:"TypeScript",python:"Python",java:"Java",go:"Go",rust:"Rust",c:"C",cpp:"C++",csharp:"C#",ruby:"Ruby",php:"PHP",swift:"Swift",kotlin:"Kotlin",html:"HTML",css:"CSS",scss:"SCSS",sql:"SQL",graphql:"GraphQL",json:"JSON",yaml:"YAML",xml:"XML",toml:"TOML",markdown:"Markdown",md:"Markdown",bash:"Bash",shell:"Shell",sh:"Shell",zsh:"Zsh",dockerfile:"Dockerfile",makefile:"Makefile",text:"Text"};function dt(t){return lt[t]||t.charAt(0).toUpperCase()+t.slice(1)}function ct(t){let e=at(t);return e=e.replaceAll(/```([\s\S]*?)```/g,'<pre class="md-code"><code>$1</code></pre>'),e=e.replaceAll(/`([^`]+)`/g,'<code class="md-inline-code">$1</code>'),e=e.replaceAll(/^###[^\S\n]+(.+)$/gm,"<h3>$1</h3>"),e=e.replaceAll(/^##[^\S\n]+(.+)$/gm,"<h2>$1</h2>"),e=e.replaceAll(/^#[^\S\n]+(.+)$/gm,"<h1>$1</h1>"),e=e.replaceAll(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replaceAll(/\*([^*]+)\*/g,"<em>$1</em>"),e=e.replaceAll(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replaceAll(/(?:^|\n)-\s+(.+)(?=\n|$)/g,(t,e)=>`\n<ul><li>${e}</li></ul>`),e=e.replaceAll(/<ul>\s*<li>([\s\S]*?)<\/li>\s*<\/ul>\n<ul>/g,"<ul><li>$1</li>"),e=e.split(/\n\n+/).map(t=>/^(<h\d|<pre|<ul|<ol|<blockquote)/.test(t.trim())?t:`<p>${t.replaceAll("\n","<br/>")}</p>`).join("\n"),e}
|
|
1853
1987
|
/**
|
|
1854
1988
|
* @license
|
|
1855
1989
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1856
1990
|
* SPDX-License-Identifier: MIT
|
|
1857
|
-
*/function ht(t,i){var o,s,r,c,
|
|
1991
|
+
*/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){var o,s,r,d,c,h,u,p;const f=null===(o=t.text)||void 0===o?void 0:o.includes("[ERROR_START]"),g={error:!!t.error||f,introduction:!!t.introduction,[t.sender]:!0};return i`
|
|
1858
1992
|
<div
|
|
1859
1993
|
class="message ${a(g)}"
|
|
1860
1994
|
part="message"
|
|
@@ -1862,43 +1996,54 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1862
1996
|
data-id="${t.id}"
|
|
1863
1997
|
>
|
|
1864
1998
|
<div class="message__content" part="message-content">
|
|
1865
|
-
${f?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],
|
|
1999
|
+
${f?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`
|
|
1866
2000
|
<div class="message__error-container" part="message-error">
|
|
1867
|
-
${t?
|
|
1868
|
-
<div class="message__error-description" part="message-error-description">${
|
|
2001
|
+
${t?i`<div class="message__error-title" part="message-error-title">${t}</div>`:""}
|
|
2002
|
+
<div class="message__error-description" part="message-error-description">${n}</div>
|
|
1869
2003
|
</div>
|
|
1870
|
-
`}return
|
|
2004
|
+
`}return i`${t}`}(null!==(r=null===(s=t.text)||void 0===s?void 0:s.trim())&&void 0!==r?r:""):(null===(d=null==t?void 0:t.metadata)||void 0===d?void 0:d.renderAsHtml)?l(null!==(h=null===(c=t.text)||void 0===c?void 0:c.trim())&&void 0!==h?h:""):l((null!==(p=null===(u=t.text)||void 0===u?void 0:u.trim())&&void 0!==p?p:"").replaceAll("\n","<br>"))}
|
|
1871
2005
|
</div>
|
|
1872
|
-
${t.files&&t.files.length>0?
|
|
2006
|
+
${t.files&&t.files.length>0?i`
|
|
1873
2007
|
<div class="message__attachments" part="message-attachments" role="list" aria-label="${m("Attached files")}">
|
|
1874
|
-
${t.files.map(t=>
|
|
1875
|
-
<nr-dropdown
|
|
1876
|
-
trigger="hover"
|
|
2008
|
+
${t.files.map(t=>i`
|
|
2009
|
+
<nr-dropdown
|
|
2010
|
+
trigger="hover"
|
|
1877
2011
|
placement="top-end"
|
|
1878
2012
|
size="small"
|
|
1879
2013
|
class="message-file-preview-dropdown"
|
|
1880
2014
|
>
|
|
1881
|
-
<
|
|
2015
|
+
<div
|
|
1882
2016
|
slot="trigger"
|
|
1883
|
-
class="
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2017
|
+
class="file-thumb file-thumb--message"
|
|
2018
|
+
role="button"
|
|
2019
|
+
tabindex="0"
|
|
2020
|
+
title="${t.name}"
|
|
2021
|
+
@click=${()=>{var e;return null===(e=n.onFileClick)||void 0===e?void 0:e.call(n,t)}}
|
|
2022
|
+
>
|
|
2023
|
+
${ht(t.mimeType)&&(t.url||t.previewUrl)?i`
|
|
2024
|
+
<img
|
|
2025
|
+
class="file-thumb__image"
|
|
2026
|
+
src="${t.previewUrl||t.url}"
|
|
2027
|
+
alt="${t.name}"
|
|
2028
|
+
/>
|
|
2029
|
+
`:i`
|
|
2030
|
+
<div class="file-thumb__ext" data-ext="${ut(t.name,t.mimeType)}">
|
|
2031
|
+
<span class="file-thumb__ext-label">${ut(t.name,t.mimeType)}</span>
|
|
2032
|
+
</div>
|
|
2033
|
+
`}
|
|
2034
|
+
</div>
|
|
2035
|
+
|
|
1889
2036
|
<div slot="content" class="message-file-preview-content">
|
|
1890
|
-
${
|
|
1891
|
-
<img
|
|
1892
|
-
src="${t.previewUrl||t.url}"
|
|
2037
|
+
${ht(t.mimeType)&&(t.url||t.previewUrl)?i`
|
|
2038
|
+
<img
|
|
2039
|
+
src="${t.previewUrl||t.url}"
|
|
1893
2040
|
alt="${t.name}"
|
|
1894
2041
|
class="message-file-preview-image"
|
|
1895
2042
|
/>
|
|
1896
|
-
`:
|
|
1897
|
-
<
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
class="message-file-preview-icon"
|
|
1901
|
-
></nr-icon>
|
|
2043
|
+
`:i`
|
|
2044
|
+
<div class="file-preview-ext" data-ext="${ut(t.name,t.mimeType)}">
|
|
2045
|
+
${ut(t.name,t.mimeType)}
|
|
2046
|
+
</div>
|
|
1902
2047
|
`}
|
|
1903
2048
|
<div class="message-file-preview-info">
|
|
1904
2049
|
<div class="message-file-preview-name" title="${t.name}">${t.name}</div>
|
|
@@ -1908,7 +2053,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1908
2053
|
</div>
|
|
1909
2054
|
</div>
|
|
1910
2055
|
</nr-dropdown>
|
|
1911
|
-
|
|
2056
|
+
`)}
|
|
1912
2057
|
</div>
|
|
1913
2058
|
`:e}
|
|
1914
2059
|
<div class="message__footer" part="message-footer">
|
|
@@ -1920,30 +2065,30 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1920
2065
|
size="small"
|
|
1921
2066
|
color="#9ca3af"
|
|
1922
2067
|
class="message__copy"
|
|
1923
|
-
@click=${()=>
|
|
1924
|
-
@keydown=${e=>
|
|
2068
|
+
@click=${()=>n.onCopy(t)}
|
|
2069
|
+
@keydown=${e=>n.onCopyKeydown(e,t)}
|
|
1925
2070
|
title="${m("Copy message")}"
|
|
1926
2071
|
aria-label="${m("Copy message")}"
|
|
1927
2072
|
role="button"
|
|
1928
2073
|
tabindex="0"
|
|
1929
2074
|
></nr-icon>
|
|
1930
2075
|
</div>
|
|
1931
|
-
${t.error?
|
|
2076
|
+
${t.error?i`
|
|
1932
2077
|
<nr-button
|
|
1933
2078
|
type="secondary"
|
|
1934
2079
|
size="small"
|
|
1935
2080
|
class="message__retry"
|
|
1936
2081
|
part="retry-button"
|
|
1937
|
-
@click=${()=>
|
|
1938
|
-
@keydown=${
|
|
2082
|
+
@click=${()=>n.onRetry(t)}
|
|
2083
|
+
@keydown=${n.onRetryKeydown}
|
|
1939
2084
|
aria-label="${m("Retry message")}"
|
|
1940
2085
|
>
|
|
1941
2086
|
${m("Retry")}
|
|
1942
2087
|
</nr-button>`:e}
|
|
1943
2088
|
</div>
|
|
1944
|
-
`}function
|
|
2089
|
+
`}function ft(t,n,o,s){return i`
|
|
1945
2090
|
<div class="messages" part="messages">
|
|
1946
|
-
${0===t.length?
|
|
2091
|
+
${0===t.length?i`
|
|
1947
2092
|
<div class="empty-state" part="empty-state">
|
|
1948
2093
|
<slot name="empty-state">
|
|
1949
2094
|
<div class="empty-state__content">
|
|
@@ -1952,8 +2097,8 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1952
2097
|
</slot>
|
|
1953
2098
|
</div>
|
|
1954
2099
|
`:e}
|
|
1955
|
-
${t.map(t=>
|
|
1956
|
-
${
|
|
2100
|
+
${t.map(t=>pt(t,s))}
|
|
2101
|
+
${n}
|
|
1957
2102
|
${o}
|
|
1958
2103
|
</div>
|
|
1959
2104
|
`}
|
|
@@ -1961,9 +2106,9 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1961
2106
|
* @license
|
|
1962
2107
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1963
2108
|
* SPDX-License-Identifier: MIT
|
|
1964
|
-
*/function
|
|
2109
|
+
*/function mt(t,n,o){return n.length>0?i`
|
|
1965
2110
|
<div class="suggestion-container" part="suggestions">
|
|
1966
|
-
${
|
|
2111
|
+
${n.map(t=>function(t,e){return i`
|
|
1967
2112
|
<div
|
|
1968
2113
|
class="suggestion ${a({"suggestion--disabled":!1===t.enabled})}"
|
|
1969
2114
|
part="suggestion"
|
|
@@ -1983,53 +2128,80 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1983
2128
|
* @license
|
|
1984
2129
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1985
2130
|
* SPDX-License-Identifier: MIT
|
|
1986
|
-
*/function
|
|
2131
|
+
*/function gt(t,e,n){const o=(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"},s=t=>t.startsWith("image/");return i`
|
|
1987
2132
|
<div class="context-tags-row" part="context-tags">
|
|
1988
|
-
${
|
|
1989
|
-
<nr-dropdown
|
|
1990
|
-
trigger="hover"
|
|
2133
|
+
${d(t,t=>t.id,t=>i`
|
|
2134
|
+
<nr-dropdown
|
|
2135
|
+
trigger="hover"
|
|
1991
2136
|
placement="top"
|
|
1992
2137
|
size="small"
|
|
1993
2138
|
class="file-preview-dropdown"
|
|
1994
2139
|
>
|
|
1995
|
-
<
|
|
2140
|
+
<div
|
|
1996
2141
|
slot="trigger"
|
|
1997
|
-
class="
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
@
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2142
|
+
class="file-thumb ${t.isUploading?"file-thumb--uploading":""}"
|
|
2143
|
+
role="button"
|
|
2144
|
+
tabindex="0"
|
|
2145
|
+
title="${t.name}"
|
|
2146
|
+
@click=${()=>null==n?void 0:n(t)}
|
|
2147
|
+
>
|
|
2148
|
+
${s(t.mimeType)&&(t.previewUrl||t.url)?i`
|
|
2149
|
+
<img
|
|
2150
|
+
class="file-thumb__image"
|
|
2151
|
+
src="${t.previewUrl||t.url}"
|
|
2152
|
+
alt="${t.name}"
|
|
2153
|
+
/>
|
|
2154
|
+
`:i`
|
|
2155
|
+
<div class="file-thumb__ext" data-ext="${o(t.name,t.mimeType)}">
|
|
2156
|
+
<span class="file-thumb__ext-label">${o(t.name,t.mimeType)}</span>
|
|
2157
|
+
</div>
|
|
2158
|
+
`}
|
|
2159
|
+
${t.isUploading?i`
|
|
2160
|
+
<div class="file-thumb__spinner" aria-label="${m("Uploading")}">
|
|
2161
|
+
<span class="file-thumb__spinner-ring"></span>
|
|
2162
|
+
</div>
|
|
2163
|
+
`:""}
|
|
2164
|
+
<button
|
|
2165
|
+
type="button"
|
|
2166
|
+
class="file-thumb__remove"
|
|
2167
|
+
aria-label="${m("Remove file")}"
|
|
2168
|
+
title="${m("Remove file")}"
|
|
2169
|
+
@click=${i=>{i.stopPropagation(),e(t.id)}}
|
|
2170
|
+
>
|
|
2171
|
+
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round">
|
|
2172
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
2173
|
+
<line x1="6" y1="18" x2="18" y2="6"/>
|
|
2174
|
+
</svg>
|
|
2175
|
+
</button>
|
|
2176
|
+
</div>
|
|
2177
|
+
|
|
2005
2178
|
<div slot="content" class="file-preview-content">
|
|
2006
|
-
${
|
|
2007
|
-
<img
|
|
2008
|
-
src="${t.previewUrl||t.url}"
|
|
2179
|
+
${s(t.mimeType)&&(t.url||t.previewUrl)?i`
|
|
2180
|
+
<img
|
|
2181
|
+
src="${t.previewUrl||t.url}"
|
|
2009
2182
|
alt="${t.name}"
|
|
2010
2183
|
class="file-preview-image"
|
|
2011
2184
|
/>
|
|
2012
|
-
`:
|
|
2013
|
-
<
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
class="file-preview-icon"
|
|
2017
|
-
></nr-icon>
|
|
2185
|
+
`:i`
|
|
2186
|
+
<div class="file-preview-ext" data-ext="${o(t.name,t.mimeType)}">
|
|
2187
|
+
${o(t.name,t.mimeType)}
|
|
2188
|
+
</div>
|
|
2018
2189
|
`}
|
|
2019
2190
|
<div class="file-preview-info">
|
|
2020
2191
|
<div class="file-preview-name" title="${t.name}">${t.name}</div>
|
|
2021
2192
|
<div class="file-preview-details">
|
|
2022
2193
|
<span>${(t=>{if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,e)*100)/100+" "+["Bytes","KB","MB","GB"][e]})(t.size)}</span>
|
|
2194
|
+
${t.isUploading?i`<span> · ${m("Uploading…")}</span>`:""}
|
|
2023
2195
|
</div>
|
|
2024
2196
|
</div>
|
|
2025
2197
|
</div>
|
|
2026
2198
|
</nr-dropdown>
|
|
2027
|
-
|
|
2199
|
+
`)}
|
|
2028
2200
|
</div>
|
|
2029
|
-
`}function
|
|
2201
|
+
`}function vt(t,n){return i`
|
|
2030
2202
|
<div class="action-buttons-row">
|
|
2031
2203
|
<div class="action-buttons-left">
|
|
2032
|
-
${t.enableFileUpload?function(t,e){return
|
|
2204
|
+
${t.enableFileUpload?function(t,e){return i`
|
|
2033
2205
|
<nr-dropdown
|
|
2034
2206
|
.items=${t.fileUploadItems}
|
|
2035
2207
|
trigger="click"
|
|
@@ -2052,8 +2224,8 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2052
2224
|
Attach
|
|
2053
2225
|
</nr-button>
|
|
2054
2226
|
</nr-dropdown>
|
|
2055
|
-
`}(t,
|
|
2056
|
-
${t.enableModuleSelection&&t.moduleOptions.length>0?function(t,e){return
|
|
2227
|
+
`}(t,n):e}
|
|
2228
|
+
${t.enableModuleSelection&&t.moduleOptions.length>0?function(t,e){return i`
|
|
2057
2229
|
<nr-select
|
|
2058
2230
|
.options=${t.moduleOptions}
|
|
2059
2231
|
.value=${t.selectedModules}
|
|
@@ -2073,17 +2245,17 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2073
2245
|
${t.renderModuleDisplay()}
|
|
2074
2246
|
</span>
|
|
2075
2247
|
</nr-select>
|
|
2076
|
-
`}(t,
|
|
2248
|
+
`}(t,n):e}
|
|
2077
2249
|
</div>
|
|
2078
2250
|
|
|
2079
2251
|
<div class="action-buttons-right">
|
|
2080
|
-
${t.showAudioButton&&!t.isQueryRunning?
|
|
2252
|
+
${t.showAudioButton&&!t.isQueryRunning?i`
|
|
2081
2253
|
<!-- Speech-to-text: mic + keyboard indicator -->
|
|
2082
2254
|
<button
|
|
2083
2255
|
class="audio-mic-btn"
|
|
2084
2256
|
title="${m("Record speech to text")}"
|
|
2085
2257
|
?disabled=${t.disabled}
|
|
2086
|
-
@click=${()=>{var t;return null===(t=
|
|
2258
|
+
@click=${()=>{var t;return null===(t=n.onAudioStart)||void 0===t?void 0:t.call(n,"transcribe")}}
|
|
2087
2259
|
aria-label="${m("Record speech to text")}"
|
|
2088
2260
|
>
|
|
2089
2261
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
@@ -2101,7 +2273,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2101
2273
|
class="audio-mic-btn"
|
|
2102
2274
|
title="${m("Send voice message")}"
|
|
2103
2275
|
?disabled=${t.disabled}
|
|
2104
|
-
@click=${()=>{var t;return null===(t=
|
|
2276
|
+
@click=${()=>{var t;return null===(t=n.onAudioStart)||void 0===t?void 0:t.call(n,"message")}}
|
|
2105
2277
|
aria-label="${m("Send voice message")}"
|
|
2106
2278
|
>
|
|
2107
2279
|
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
@@ -2114,7 +2286,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2114
2286
|
</svg>
|
|
2115
2287
|
</button>
|
|
2116
2288
|
`:e}
|
|
2117
|
-
${t.showSendButton&&(!t.disabled||t.isQueryRunning)&&(t.currentInput.trim()||t.uploadedFiles.length>0||t.isQueryRunning)?function(t,e){return
|
|
2289
|
+
${t.showSendButton&&(!t.disabled||t.isQueryRunning)&&(t.currentInput.trim()||t.uploadedFiles.length>0||t.isQueryRunning)?function(t,e){return i`
|
|
2118
2290
|
<nr-button
|
|
2119
2291
|
class="input-box__send-button"
|
|
2120
2292
|
part="send-button"
|
|
@@ -2128,18 +2300,18 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2128
2300
|
>
|
|
2129
2301
|
${t.isQueryRunning?m("Stop"):m("Send")}
|
|
2130
2302
|
</nr-button>
|
|
2131
|
-
`}(t,
|
|
2303
|
+
`}(t,n):e}
|
|
2132
2304
|
</div>
|
|
2133
2305
|
</div>
|
|
2134
|
-
`}function
|
|
2306
|
+
`}function bt(t,n){return t.audioRecording.active?i`
|
|
2135
2307
|
<div class="input-box" part="input-box">
|
|
2136
2308
|
<div class="input-container" part="input-container">
|
|
2137
|
-
${function(t,e){const{duration:
|
|
2309
|
+
${function(t,e){const{duration:n,bars:o}=t.audioRecording,s="transcribe"===t.audioMode,r=m(s?"Convert to text":"Send as voice message"),a=s?i`<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2138
2310
|
<rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>
|
|
2139
2311
|
<path d="M7 10h2l2 3 2-6 2 3h2"/>
|
|
2140
|
-
</svg>`:
|
|
2312
|
+
</svg>`:i`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
2141
2313
|
<path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>
|
|
2142
|
-
</svg>`;return
|
|
2314
|
+
</svg>`;return i`
|
|
2143
2315
|
<div class="audio-recording-bar">
|
|
2144
2316
|
<button
|
|
2145
2317
|
class="audio-rec-cancel"
|
|
@@ -2157,11 +2329,11 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2157
2329
|
<div class="audio-rec-indicator">
|
|
2158
2330
|
<span class="audio-rec-dot"></span>
|
|
2159
2331
|
<div class="audio-rec-wave">
|
|
2160
|
-
${o.map(t=>
|
|
2161
|
-
<div class="audio-rec-bar" style=${
|
|
2332
|
+
${o.map(t=>i`
|
|
2333
|
+
<div class="audio-rec-bar" style=${c({height:`${Math.round(24*t)}px`})}></div>
|
|
2162
2334
|
`)}
|
|
2163
2335
|
</div>
|
|
2164
|
-
<span class="audio-rec-time">${
|
|
2336
|
+
<span class="audio-rec-time">${n}</span>
|
|
2165
2337
|
</div>
|
|
2166
2338
|
|
|
2167
2339
|
<span class="audio-rec-mode-label">
|
|
@@ -2177,14 +2349,14 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2177
2349
|
${a}
|
|
2178
2350
|
</button>
|
|
2179
2351
|
</div>
|
|
2180
|
-
`}(t,
|
|
2352
|
+
`}(t,n)}
|
|
2181
2353
|
</div>
|
|
2182
2354
|
</div>
|
|
2183
|
-
`:
|
|
2355
|
+
`:i`
|
|
2184
2356
|
<div class="input-box" part="input-box">
|
|
2185
2357
|
<div class="input-container" part="input-container">
|
|
2186
2358
|
<!-- Context tags -->
|
|
2187
|
-
${t.uploadedFiles.length>0?
|
|
2359
|
+
${t.uploadedFiles.length>0?gt(t.uploadedFiles,n.onFileRemove,n.onFileClick):e}
|
|
2188
2360
|
|
|
2189
2361
|
<!-- Input area -->
|
|
2190
2362
|
<div class="input-row">
|
|
@@ -2196,15 +2368,15 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2196
2368
|
aria-multiline="true"
|
|
2197
2369
|
aria-label="${m("Chat input")}"
|
|
2198
2370
|
data-placeholder="${t.placeholder}"
|
|
2199
|
-
@input=${
|
|
2200
|
-
@keydown=${
|
|
2201
|
-
@focus=${
|
|
2202
|
-
@blur=${
|
|
2371
|
+
@input=${n.onInput}
|
|
2372
|
+
@keydown=${n.onKeydown}
|
|
2373
|
+
@focus=${n.onFocus}
|
|
2374
|
+
@blur=${n.onBlur}
|
|
2203
2375
|
></div>
|
|
2204
2376
|
</div>
|
|
2205
2377
|
|
|
2206
2378
|
<!-- Action buttons -->
|
|
2207
|
-
${
|
|
2379
|
+
${vt(t,n)}
|
|
2208
2380
|
</div>
|
|
2209
2381
|
</div>
|
|
2210
2382
|
`}
|
|
@@ -2212,70 +2384,56 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2212
2384
|
* @license
|
|
2213
2385
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2214
2386
|
* SPDX-License-Identifier: MIT
|
|
2215
|
-
*/function
|
|
2387
|
+
*/function yt(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`
|
|
2216
2388
|
<div
|
|
2217
2389
|
class="thread-item ${a({"thread-item--active":t.id===e.activeThreadId})}"
|
|
2218
|
-
@click=${()=>
|
|
2390
|
+
@click=${()=>n.onSelectThread(t.id)}
|
|
2219
2391
|
part="thread-item"
|
|
2220
2392
|
>
|
|
2221
2393
|
<div class="thread-item__header">
|
|
2222
|
-
${e.editingThreadId===t.id&&
|
|
2394
|
+
${e.editingThreadId===t.id&&n.onRenameThread?i`
|
|
2223
2395
|
<input
|
|
2224
2396
|
class="thread-item__rename-input"
|
|
2225
2397
|
type="text"
|
|
2226
2398
|
.value=${t.title||""}
|
|
2227
2399
|
@click=${t=>t.stopPropagation()}
|
|
2228
|
-
@keydown=${e=>{if("Enter"===e.key){const
|
|
2229
|
-
@blur=${e=>{const
|
|
2400
|
+
@keydown=${e=>{if("Enter"===e.key){const i=e.target.value.trim();i&&n.onRenameThread(t.id,i)}"Escape"===e.key&&n.onRenameThread(t.id,t.title||"")}}
|
|
2401
|
+
@blur=${e=>{const i=e.target.value.trim();i&&i!==t.title?n.onRenameThread(t.id,i):n.onRenameThread(t.id,t.title||"")}}
|
|
2230
2402
|
/>
|
|
2231
|
-
`:
|
|
2403
|
+
`:i`
|
|
2232
2404
|
<div class="thread-item__title">${t.title||m("New Chat")}</div>
|
|
2233
2405
|
`}
|
|
2234
2406
|
<div class="thread-item__actions">
|
|
2235
|
-
${
|
|
2407
|
+
${n.onBookmarkThread&&t.bookmarked?i`
|
|
2236
2408
|
<button
|
|
2237
|
-
class="thread-item__action-btn"
|
|
2238
|
-
title="${m("
|
|
2239
|
-
@click=${e=>{e.stopPropagation(),
|
|
2240
|
-
part="thread-rename"
|
|
2241
|
-
>
|
|
2242
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
|
2243
|
-
</button>
|
|
2244
|
-
`:""}
|
|
2245
|
-
${i.onBookmarkThread?n`
|
|
2246
|
-
<button
|
|
2247
|
-
class="thread-item__action-btn ${t.bookmarked?"thread-item__bookmark--active":""}"
|
|
2248
|
-
title="${t.bookmarked?m("Remove bookmark"):m("Bookmark conversation")}"
|
|
2249
|
-
@click=${e=>{e.stopPropagation(),i.onBookmarkThread(t.id)}}
|
|
2409
|
+
class="thread-item__action-btn thread-item__bookmark--active"
|
|
2410
|
+
title="${m("Remove bookmark")}"
|
|
2411
|
+
@click=${e=>{e.stopPropagation(),n.onBookmarkThread(t.id)}}
|
|
2250
2412
|
part="thread-bookmark"
|
|
2251
2413
|
>
|
|
2252
|
-
|
|
2253
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" 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>
|
|
2254
|
-
`:n`
|
|
2255
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" 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>
|
|
2256
|
-
`}
|
|
2414
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" 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>
|
|
2257
2415
|
</button>
|
|
2258
2416
|
`:""}
|
|
2259
|
-
${
|
|
2260
|
-
<nr-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
ok-type="danger"
|
|
2266
|
-
placement="right"
|
|
2417
|
+
${e.editingThreadId!==t.id&&(n.onRenameThread||n.onBookmarkThread||n.onDeleteThread)?i`
|
|
2418
|
+
<nr-dropdown
|
|
2419
|
+
trigger="click"
|
|
2420
|
+
placement="bottom-end"
|
|
2421
|
+
size="small"
|
|
2422
|
+
auto-close
|
|
2267
2423
|
@click=${t=>t.stopPropagation()}
|
|
2268
|
-
@nr-
|
|
2424
|
+
@nr-dropdown-item-click=${e=>{var i,o;const s=null===(o=null===(i=e.detail)||void 0===i?void 0:i.item)||void 0===o?void 0:o.id;"rename"===s&&n.onRenameThread?e.target.dispatchEvent(new CustomEvent("nr-thread-edit",{bubbles:!0,composed:!0,detail:{threadId:t.id}})):"bookmark"===s&&n.onBookmarkThread?n.onBookmarkThread(t.id):"delete"===s&&n.onDeleteThread&&n.onDeleteThread(t.id)}}
|
|
2425
|
+
.items=${[...n.onRenameThread?[{id:"rename",label:m("Rename")}]:[],...n.onBookmarkThread?[{id:"bookmark",label:t.bookmarked?m("Remove bookmark"):m("Bookmark")}]:[],...n.onDeleteThread?[{id:"delete",label:m("Delete")}]:[]]}
|
|
2269
2426
|
>
|
|
2270
2427
|
<button
|
|
2271
2428
|
slot="trigger"
|
|
2272
|
-
class="thread-item__action-btn thread-
|
|
2273
|
-
title="${m("
|
|
2274
|
-
part="thread-
|
|
2429
|
+
class="thread-item__action-btn thread-item__menu"
|
|
2430
|
+
title="${m("More options")}"
|
|
2431
|
+
part="thread-menu"
|
|
2432
|
+
aria-label="${m("More options")}"
|
|
2275
2433
|
>
|
|
2276
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="
|
|
2434
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" stroke="none"><circle cx="5" cy="12" r="1.8"/><circle cx="12" cy="12" r="1.8"/><circle cx="19" cy="12" r="1.8"/></svg>
|
|
2277
2435
|
</button>
|
|
2278
|
-
</nr-
|
|
2436
|
+
</nr-dropdown>
|
|
2279
2437
|
`:""}
|
|
2280
2438
|
</div>
|
|
2281
2439
|
</div>
|
|
@@ -2284,21 +2442,21 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2284
2442
|
</div>
|
|
2285
2443
|
<div class="thread-item__timestamp">${rt(t.updatedAt)}</div>
|
|
2286
2444
|
</div>
|
|
2287
|
-
`}function
|
|
2445
|
+
`}function xt(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`
|
|
2288
2446
|
<nr-modal
|
|
2289
2447
|
.open=${t.isOpen}
|
|
2290
2448
|
size="large"
|
|
2291
2449
|
title="${o.name}"
|
|
2292
|
-
@modal-close=${
|
|
2450
|
+
@modal-close=${n.onClose}
|
|
2293
2451
|
>
|
|
2294
2452
|
<div style="width: 100%; height: 75vh; display: flex; flex-direction: column; align-items: stretch; justify-content: stretch;">
|
|
2295
|
-
${s&&(o.url||o.previewUrl)?
|
|
2453
|
+
${s&&(o.url||o.previewUrl)?i`
|
|
2296
2454
|
<img
|
|
2297
2455
|
src="${o.url||o.previewUrl}"
|
|
2298
2456
|
alt="${o.name}"
|
|
2299
2457
|
style="max-width: 100%; max-height: 100%; object-fit: contain; align-self: center;"
|
|
2300
2458
|
/>
|
|
2301
|
-
`:r&&o.url?
|
|
2459
|
+
`:r&&o.url?i`
|
|
2302
2460
|
<div style="width: 100%; height: 100%; position: relative;">
|
|
2303
2461
|
<nr-document
|
|
2304
2462
|
.src="${o.url}"
|
|
@@ -2309,7 +2467,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2309
2467
|
style="width: 100%; height: 100%; display: block;"
|
|
2310
2468
|
></nr-document>
|
|
2311
2469
|
</div>
|
|
2312
|
-
`:
|
|
2470
|
+
`:i`
|
|
2313
2471
|
<div style="text-align: center; padding: 2rem; align-self: center;">
|
|
2314
2472
|
<nr-icon name="file" size="xlarge" style="margin-bottom: 1rem;"></nr-icon>
|
|
2315
2473
|
<p style="font-size: 1.1rem; font-weight: 500; margin-bottom: 0.5rem;">${o.name}</p>
|
|
@@ -2322,7 +2480,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
2322
2480
|
*/
|
|
2323
2481
|
function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,e)*100)/100+" "+["Bytes","KB","MB","GB"][e]}(o.size)}
|
|
2324
2482
|
</p>
|
|
2325
|
-
${o.url?
|
|
2483
|
+
${o.url?i`
|
|
2326
2484
|
<nr-button
|
|
2327
2485
|
type="primary"
|
|
2328
2486
|
@click=${()=>window.open(o.url,"_blank")}
|
|
@@ -2339,7 +2497,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2339
2497
|
* @license
|
|
2340
2498
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2341
2499
|
* SPDX-License-Identifier: MIT
|
|
2342
|
-
*/function
|
|
2500
|
+
*/function wt(t,n){var o;if(!t.isOpen||!t.artifact)return e;const s=t.artifact,r=dt(s.language);return i`
|
|
2343
2501
|
<div class="artifact-panel" part="artifact-panel">
|
|
2344
2502
|
<div class="artifact-panel__resize-handle" part="artifact-panel-resize-handle">
|
|
2345
2503
|
<div class="artifact-panel__resize-bar"></div>
|
|
@@ -2355,7 +2513,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2355
2513
|
type="text"
|
|
2356
2514
|
size="small"
|
|
2357
2515
|
.icon=${["copy"]}
|
|
2358
|
-
@click=${()=>
|
|
2516
|
+
@click=${()=>n.onCopy(s)}
|
|
2359
2517
|
title="${m("Copy code")}"
|
|
2360
2518
|
aria-label="${m("Copy code")}"
|
|
2361
2519
|
></nr-button>
|
|
@@ -2363,14 +2521,14 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2363
2521
|
type="text"
|
|
2364
2522
|
size="small"
|
|
2365
2523
|
.icon=${["x"]}
|
|
2366
|
-
@click=${
|
|
2524
|
+
@click=${n.onClose}
|
|
2367
2525
|
title="${m("Close panel")}"
|
|
2368
2526
|
aria-label="${m("Close panel")}"
|
|
2369
2527
|
></nr-button>
|
|
2370
2528
|
</div>
|
|
2371
2529
|
</div>
|
|
2372
2530
|
<div class="artifact-panel__content">
|
|
2373
|
-
${(null===(o=t.renderContent)||void 0===o?void 0:o.call(t,s))||function(t){switch(t.language){case"json":{let e;try{e=JSON.stringify(JSON.parse(t.content),null,2)}catch(
|
|
2531
|
+
${(null===(o=t.renderContent)||void 0===o?void 0:o.call(t,s))||function(t){switch(t.language){case"json":{let e;try{e=JSON.stringify(JSON.parse(t.content),null,2)}catch(i){e=t.content}return i`<pre class="artifact-panel__code"><code>${e}</code></pre>`}case"md":case"markdown":return i`<div class="artifact-panel__rendered-md">${l(ct(t.content))}</div>`;case"html":return i`<div class="artifact-panel__rendered-html">${l(t.content)}</div>`;case"text":case"txt":return i`<div class="artifact-panel__rendered-text">${t.content}</div>`;default:return i`<pre class="artifact-panel__code"><code>${t.content}</code></pre>`}}(s)}
|
|
2374
2532
|
</div>
|
|
2375
2533
|
</div>
|
|
2376
2534
|
</div>
|
|
@@ -2379,53 +2537,53 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2379
2537
|
* @license
|
|
2380
2538
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2381
2539
|
* SPDX-License-Identifier: MIT
|
|
2382
|
-
*/function
|
|
2540
|
+
*/function _t(t,n){return!1!==t.showMessages?i`
|
|
2383
2541
|
<div class="chatbot-content" part="content">
|
|
2384
|
-
${
|
|
2542
|
+
${ft(t.messages,mt(t.chatStarted,t.suggestions,n.suggestion),t.isTyping?function(t,n,o){if(!t)return e;const s=n===V.Dots?i`
|
|
2385
2543
|
<div class="dots">
|
|
2386
2544
|
<span></span>
|
|
2387
2545
|
<span></span>
|
|
2388
2546
|
<span></span>
|
|
2389
2547
|
</div>
|
|
2390
|
-
`:
|
|
2548
|
+
`:i`<div class="spinner"></div>`;return i`
|
|
2391
2549
|
<div class="message bot loading" part="typing-indicator">
|
|
2392
2550
|
<div class="message__content">
|
|
2393
2551
|
${s}
|
|
2394
|
-
${o?
|
|
2552
|
+
${o?i`<span class="loading-text">${o.split("").map((t,e)=>i`<span class="loading-text__char" style="animation-delay:${.04*e}s">${" "===t?" ":t}</span>`)}</span>`:e}
|
|
2395
2553
|
</div>
|
|
2396
2554
|
</div>
|
|
2397
|
-
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,
|
|
2555
|
+
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,n.message)}
|
|
2398
2556
|
<slot name="messages"></slot>
|
|
2399
2557
|
</div>
|
|
2400
|
-
`:t.suggestions&&t.suggestions.length>0?
|
|
2558
|
+
`:t.suggestions&&t.suggestions.length>0?i`
|
|
2401
2559
|
<div class="input-only-suggestions" part="input-only-suggestions">
|
|
2402
|
-
${
|
|
2560
|
+
${mt(0,t.suggestions,n.suggestion)}
|
|
2403
2561
|
</div>
|
|
2404
|
-
`:e}function
|
|
2562
|
+
`:e}function $t(t,n){var o;const s=t.enableArtifacts&&(null===(o=t.artifactPanel)||void 0===o?void 0:o.isOpen);return i`
|
|
2405
2563
|
<div class="chatbot-container ${a({"chatbot-container--with-sidebar":t.enableThreads&&t.isThreadSidebarOpen,"chatbot-container--with-artifact-panel":!!s})}" part="container">
|
|
2406
2564
|
|
|
2407
|
-
${t.enableThreads&&t.isThreadSidebarOpen&&t.threadSidebar&&
|
|
2565
|
+
${t.enableThreads&&t.isThreadSidebarOpen&&t.threadSidebar&&n.threadSidebar?function(t,n){const o=t.threads.filter(t=>t.bookmarked),s=t.threads.filter(t=>!t.bookmarked);return i`
|
|
2408
2566
|
<div class="thread-sidebar" part="thread-sidebar">
|
|
2409
2567
|
<div class="thread-sidebar__header">
|
|
2410
2568
|
<h3>${m("Conversations")}</h3>
|
|
2411
2569
|
</div>
|
|
2412
2570
|
|
|
2413
2571
|
<div class="thread-list">
|
|
2414
|
-
${o.length>0?
|
|
2572
|
+
${o.length>0?i`
|
|
2415
2573
|
<div class="thread-section" part="thread-section-bookmarks">
|
|
2416
2574
|
<div class="thread-section__label">
|
|
2417
2575
|
<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>
|
|
2418
2576
|
${m("Bookmarks")}
|
|
2419
2577
|
</div>
|
|
2420
|
-
${
|
|
2578
|
+
${d(o,t=>t.id,e=>yt(e,t,n))}
|
|
2421
2579
|
</div>
|
|
2422
2580
|
`:e}
|
|
2423
|
-
${s.length>0||0===o.length?
|
|
2424
|
-
${o.length>0?
|
|
2581
|
+
${s.length>0||0===o.length?i`
|
|
2582
|
+
${o.length>0?i`
|
|
2425
2583
|
<div class="thread-section__label">${m("All Conversations")}</div>
|
|
2426
2584
|
`:e}
|
|
2427
|
-
${
|
|
2428
|
-
${0===s.length&&0===o.length?
|
|
2585
|
+
${d(s,t=>t.id,e=>yt(e,t,n))}
|
|
2586
|
+
${0===s.length&&0===o.length?i`
|
|
2429
2587
|
<p class="empty-msg">${m("No conversations yet")}</p>
|
|
2430
2588
|
`:e}
|
|
2431
2589
|
`:e}
|
|
@@ -2438,44 +2596,44 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2438
2596
|
* @license
|
|
2439
2597
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2440
2598
|
* SPDX-License-Identifier: MIT
|
|
2441
|
-
*/(t.threadSidebar,
|
|
2599
|
+
*/(t.threadSidebar,n.threadSidebar):""}
|
|
2442
2600
|
|
|
2443
2601
|
<div class="chatbot-main" part="main">
|
|
2444
|
-
${function(t,
|
|
2602
|
+
${function(t,n){var o;return t.enableThreads?i`
|
|
2445
2603
|
<div class="chatbot-header" part="chatbot-header">
|
|
2446
2604
|
<nr-button
|
|
2447
2605
|
type="text"
|
|
2448
2606
|
size="small"
|
|
2449
2607
|
.icon=${["panel-left"]}
|
|
2450
|
-
@click=${
|
|
2608
|
+
@click=${n.onToggleThreadSidebar}
|
|
2451
2609
|
title="${m(t.isThreadSidebarOpen?"Hide threads":"Show threads")}"
|
|
2452
2610
|
aria-label="${m(t.isThreadSidebarOpen?"Hide threads":"Show threads")}"
|
|
2453
2611
|
></nr-button>
|
|
2454
|
-
${t.enableThreadCreation&&t.messages.length>0?
|
|
2612
|
+
${t.enableThreadCreation&&t.messages.length>0?i`
|
|
2455
2613
|
<nr-button
|
|
2456
2614
|
type="text"
|
|
2457
2615
|
size="small"
|
|
2458
2616
|
.icon=${["square-pen"]}
|
|
2459
|
-
@click=${null===(o=
|
|
2617
|
+
@click=${null===(o=n.threadSidebar)||void 0===o?void 0:o.onCreateNew}
|
|
2460
2618
|
title="${m("New conversation")}"
|
|
2461
2619
|
aria-label="${m("New conversation")}"
|
|
2462
2620
|
></nr-button>
|
|
2463
2621
|
`:""}
|
|
2464
2622
|
</div>
|
|
2465
|
-
`:e}(t,
|
|
2623
|
+
`:e}(t,n)}
|
|
2466
2624
|
|
|
2467
2625
|
<slot name="header"></slot>
|
|
2468
2626
|
|
|
2469
|
-
${
|
|
2627
|
+
${_t(t,n)}
|
|
2470
2628
|
|
|
2471
|
-
${
|
|
2629
|
+
${bt(t.inputBox,n.inputBox)}
|
|
2472
2630
|
|
|
2473
2631
|
<slot name="footer"></slot>
|
|
2474
2632
|
</div>
|
|
2475
2633
|
|
|
2476
|
-
${s&&t.artifactPanel&&
|
|
2634
|
+
${s&&t.artifactPanel&&n.artifactPanel?wt(t.artifactPanel,n.artifactPanel):""}
|
|
2477
2635
|
|
|
2478
|
-
${t.isDragging?function(t,e){return
|
|
2636
|
+
${t.isDragging?function(t,e){return i`
|
|
2479
2637
|
<div
|
|
2480
2638
|
class="file-upload-area ${t.isDragging?"file-upload-area--dragging":""}"
|
|
2481
2639
|
part="file-upload-area"
|
|
@@ -2495,12 +2653,12 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2495
2653
|
* @license
|
|
2496
2654
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2497
2655
|
* SPDX-License-Identifier: MIT
|
|
2498
|
-
*/({isDragging:t.isDragging},
|
|
2656
|
+
*/({isDragging:t.isDragging},n.fileUploadArea):""}
|
|
2499
2657
|
|
|
2500
|
-
${t.urlModal&&
|
|
2658
|
+
${t.urlModal&&n.urlModal?function(t,n){return i`
|
|
2501
2659
|
<nr-modal
|
|
2502
2660
|
?open=${t.isOpen}
|
|
2503
|
-
@nr-modal-close=${
|
|
2661
|
+
@nr-modal-close=${n.onClose}
|
|
2504
2662
|
part="url-modal"
|
|
2505
2663
|
>
|
|
2506
2664
|
<div slot="header">${m("Add URL")}</div>
|
|
@@ -2514,8 +2672,8 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2514
2672
|
.value=${t.urlInput}
|
|
2515
2673
|
placeholder="${m("Enter URL...")}"
|
|
2516
2674
|
?disabled=${t.isLoading}
|
|
2517
|
-
@nr-input=${
|
|
2518
|
-
@keydown=${
|
|
2675
|
+
@nr-input=${n.onUrlInputChange}
|
|
2676
|
+
@keydown=${n.onUrlInputKeydown}
|
|
2519
2677
|
>
|
|
2520
2678
|
<nr-label slot="label">${m("URL")}</nr-label>
|
|
2521
2679
|
</nr-input>
|
|
@@ -2526,7 +2684,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2526
2684
|
.icon=${["paperclip"]}
|
|
2527
2685
|
size="small"
|
|
2528
2686
|
?disabled=${t.isLoading}
|
|
2529
|
-
@click=${
|
|
2687
|
+
@click=${n.onAttachFile}
|
|
2530
2688
|
title="${m("Load file from URL")}"
|
|
2531
2689
|
style="margin-left: 0.5rem;"
|
|
2532
2690
|
>
|
|
@@ -2534,7 +2692,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2534
2692
|
</nr-col>
|
|
2535
2693
|
</nr-row>
|
|
2536
2694
|
|
|
2537
|
-
${t.error?
|
|
2695
|
+
${t.error?i`
|
|
2538
2696
|
<nr-alert
|
|
2539
2697
|
type="error"
|
|
2540
2698
|
closable
|
|
@@ -2544,7 +2702,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2544
2702
|
</nr-alert>
|
|
2545
2703
|
`:e}
|
|
2546
2704
|
|
|
2547
|
-
${t.selectedFileName?
|
|
2705
|
+
${t.selectedFileName?i`
|
|
2548
2706
|
<nr-alert
|
|
2549
2707
|
type="success"
|
|
2550
2708
|
style="margin-top: 1rem;"
|
|
@@ -2553,7 +2711,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2553
2711
|
</nr-alert>
|
|
2554
2712
|
`:e}
|
|
2555
2713
|
|
|
2556
|
-
${t.isLoading?
|
|
2714
|
+
${t.isLoading?i`
|
|
2557
2715
|
<nr-alert
|
|
2558
2716
|
type="info"
|
|
2559
2717
|
style="margin-top: 1rem;"
|
|
@@ -2568,7 +2726,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2568
2726
|
type="default"
|
|
2569
2727
|
size="small"
|
|
2570
2728
|
?disabled=${t.isLoading}
|
|
2571
|
-
@click=${
|
|
2729
|
+
@click=${n.onClose}
|
|
2572
2730
|
>
|
|
2573
2731
|
${m("Cancel")}
|
|
2574
2732
|
</nr-button>
|
|
@@ -2577,13 +2735,13 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2577
2735
|
size="small"
|
|
2578
2736
|
?disabled=${!t.urlInput&&!t.selectedFileName||t.isLoading}
|
|
2579
2737
|
?loading=${t.isLoading}
|
|
2580
|
-
@click=${
|
|
2738
|
+
@click=${n.onConfirm}
|
|
2581
2739
|
>
|
|
2582
2740
|
${m("Add")}
|
|
2583
2741
|
</nr-button>
|
|
2584
2742
|
</div>
|
|
2585
2743
|
</nr-modal>
|
|
2586
|
-
`}(t.urlModal,
|
|
2744
|
+
`}(t.urlModal,n.urlModal):""}
|
|
2587
2745
|
|
|
2588
2746
|
<slot></slot>
|
|
2589
2747
|
</div>
|
|
@@ -2592,12 +2750,12 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2592
2750
|
* @license
|
|
2593
2751
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2594
2752
|
* SPDX-License-Identifier: MIT
|
|
2595
|
-
*/var
|
|
2753
|
+
*/var kt=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 St={active:!1,duration:"00:00",bars:[]};class Pt{constructor(t){this.state=Object.assign({},St),this._mediaRecorder=null,this._audioChunks=[],this._waveformSamples=[],this._analyser=null,this._timer=null,this._animFrame=0,this._startTime=0,this._stopResolve=null,this.host=t,t.addController(this)}hostConnected(){}hostDisconnected(){this.cancel()}start(){return kt(this,void 0,void 0,function*(){try{const t=yield navigator.mediaDevices.getUserMedia({audio:!0});this._audioChunks=[],this._waveformSamples=[];const e=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/aac",""].find(t=>!t||MediaRecorder.isTypeSupported(t))||"";this._mediaRecorder=new MediaRecorder(t,e?{mimeType:e}:void 0);const i=new AudioContext;"suspended"===i.state&&(yield i.resume());const n=i.createMediaStreamSource(t);this._analyser=i.createAnalyser(),this._analyser.fftSize=256,this._analyser.smoothingTimeConstant=.3,n.connect(this._analyser),this._mediaRecorder.ondataavailable=t=>{t.data.size>0&&this._audioChunks.push(t.data)},this._mediaRecorder.onstop=()=>{var e;t.getTracks().forEach(t=>t.stop()),i.close().catch(()=>{}),this._timer&&clearInterval(this._timer),cancelAnimationFrame(this._animFrame),this._analyser=null,null===(e=this._stopResolve)||void 0===e||e.call(this,[...this._audioChunks]),this._stopResolve=null},this._mediaRecorder.start(100),this._startTime=Date.now(),this.state={active:!0,duration:"00:00",bars:[]},this.host.requestUpdate(),this._timer=setInterval(()=>{const t=Math.floor((Date.now()-this._startTime)/1e3),e=Math.floor(t/60).toString().padStart(2,"0"),i=(t%60).toString().padStart(2,"0");this.state=Object.assign(Object.assign({},this.state),{duration:`${e}:${i}`}),this.host.requestUpdate()},500);let o=0;const s=()=>{if(!this._analyser||!this.state.active)return;const t=performance.now();if(t-o>80){o=t;const e=this._analyser.frequencyBinCount,i=new Uint8Array(e);this._analyser.getByteFrequencyData(i);let n=i.reduce((t,e)=>t+e,0)/e;if(n<1){this._analyser.getByteTimeDomainData(i);let t=0;for(let n=0;n<e;n++){const e=Math.abs(i[n]-128);e>t&&(t=e)}n=t}const s=Math.min(1,n/128);this._waveformSamples.push(s);const r=this._waveformSamples.slice(-40).map(t=>Math.max(.08,t));this.state=Object.assign(Object.assign({},this.state),{bars:r}),this.host.requestUpdate()}this._animFrame=requestAnimationFrame(s)};this._animFrame=requestAnimationFrame(s)}catch(t){console.error("[ChatbotAudio] Mic access denied")}})}cancel(){var t;"recording"===(null===(t=this._mediaRecorder)||void 0===t?void 0:t.state)&&(this._stopResolve=null,this._mediaRecorder.stop()),this._audioChunks=[],this._waveformSamples=[],this._timer&&clearInterval(this._timer),cancelAnimationFrame(this._animFrame),this._analyser=null,this.state=Object.assign({},St),this.host.requestUpdate()}stop(){return kt(this,void 0,void 0,function*(){var t;if(!this._mediaRecorder||"recording"!==this._mediaRecorder.state)return null;const e=this.state.duration,i=yield new Promise(t=>{this._stopResolve=t,this._mediaRecorder.stop()});yield new Promise(t=>setTimeout(t,200)),this.state=Object.assign({},St),this.host.requestUpdate();const n=(null===(t=this._mediaRecorder)||void 0===t?void 0:t.mimeType)||"audio/webm",o=new Blob(i,{type:n});this._audioChunks=[],this._waveformSamples=[];try{const{compressToOpus:t}=yield Promise.resolve().then(function(){return ei}),{blob:i,mimeType:s}=yield t(o,n);return{blob:i,mimeType:s,duration:e}}catch(t){return{blob:o,mimeType:n,duration:e}}})}}
|
|
2596
2754
|
/**
|
|
2597
2755
|
* @license
|
|
2598
2756
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2599
2757
|
* SPDX-License-Identifier: MIT
|
|
2600
|
-
*/var St=function(t,e,n,i){for(var o,s=arguments.length,r=s<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i,a=t.length-1;a>=0;a--)(o=t[a])&&(r=(s<3?o(r):s>3?o(e,n,r):o(e,n))||r);return s>3&&r&&Object.defineProperty(e,n,r),r},Pt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};let Mt=class extends((t=>B(F(L(H(t)))))(i)){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.controllerUnsubscribes=[],this._audio=new kt(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,n,i;null===(t=this.shadowRoot)||void 0===t||t.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(i){const t=i.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===(n=this.shadowRoot)||void 0===n||n.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-selection-value]");if(i){const t=i.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}}),null===(i=this.shadowRoot)||void 0===i||i.addEventListener("keydown",t=>{var e,n,i,o;const s=t;if("Enter"!==s.key&&" "!==s.key)return;const r=null===(n=(e=s.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(r){s.preventDefault();const t=r.dataset.artifactId;return void(t&&this.handleArtifactClick(t))}const a=null===(o=(i=s.target).closest)||void 0===o?void 0:o.call(i,"[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,n,i,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===(n=t.messages)||void 0===n?void 0:n.some(t=>{var e,n;return(null===(n=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds)||void 0===n?void 0:n.length)>0});e||(this.isArtifactPanelOpen=!1,this.selectedArtifact=null)}if(this.enableArtifacts&&(null===(i=t.messages)||void 0===i?void 0:i.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),n=null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.artifactIds;if(null==n?void 0:n.length){const t=n[n.length-1];if((null===(s=this.selectedArtifact)||void 0===s?void 0:s.id)!==t){const e=this.getArtifactPlugin(),n=null==e?void 0:e.getArtifact(t);n&&(this.selectedArtifact=n,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)}render(){var t;const e={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},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId}:void 0,isDragging:!1,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer()}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName}:void 0},i={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 n;null===(n=this.controller)||void 0===n||n.renameThread(t,e),this._editingThreadId=void 0}}:void 0,fileUploadArea:{onDrop:()=>{},onDragOver:()=>{},onDragLeave:()=>{}},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 n`
|
|
2758
|
+
*/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())})};let Et=class extends((t=>L(D(B(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.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)}render(){var t;const e={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},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId}:void 0,isDragging:!1,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer()}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName}:void 0},n={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:{onDrop:()=>{},onDragOver:()=>{},onDragLeave:()=>{}},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`
|
|
2601
2759
|
<div
|
|
2602
2760
|
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})}"
|
|
2603
2761
|
dir=${this.isRTL?"rtl":"ltr"}
|
|
@@ -2607,177 +2765,177 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2607
2765
|
data-mode="${this.mode}"
|
|
2608
2766
|
part="chat-container">
|
|
2609
2767
|
|
|
2610
|
-
${
|
|
2768
|
+
${$t(e,n)}
|
|
2611
2769
|
</div>
|
|
2612
2770
|
|
|
2613
|
-
${
|
|
2614
|
-
`}renderModuleSelectedDisplay(){const t=this.selectedModules.length;if(0===t)return
|
|
2771
|
+
${xt({isOpen:this.isFilePreviewModalOpen,file:this.previewFile},{onClose:this.handleFilePreviewModalClose.bind(this)})}
|
|
2772
|
+
`}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`
|
|
2615
2773
|
<span class="module-display-single">
|
|
2616
|
-
${(null==t?void 0:t.icon)?
|
|
2774
|
+
${(null==t?void 0:t.icon)?i`<nr-icon name="${t.icon}" size="small"></nr-icon>`:e}
|
|
2617
2775
|
${(null==t?void 0:t.name)||this.selectedModules[0]}
|
|
2618
2776
|
</span>
|
|
2619
|
-
`}return
|
|
2777
|
+
`}return i`
|
|
2620
2778
|
<span class="module-display-multiple">
|
|
2621
2779
|
${t} ${m("modules selected")}
|
|
2622
2780
|
</span>
|
|
2623
|
-
`}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 Pt(this,void 0,void 0,function*(){var t;const e=yield this._audio.stop();if(!e)return;const n=this._audioMode;null===(t=this.onAudioRecorded)||void 0===t||t.call(this,e.blob,e.mimeType,e.duration,n),this.dispatchEvent(new CustomEvent("nr-chatbot-audio-recorded",{detail:{blob:e.blob,mimeType:e.mimeType,duration:e.duration,mode:n},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 n=()=>{this.dispatchEventWithMetadata("nr-chatbot-message-copied",{metadata:{messageId:t.id}})};navigator.clipboard?navigator.clipboard.writeText(e).then(n).catch(()=>{this.copyViaFallback(e,n)}):this.copyViaFallback(e,n)}copyViaFallback(t,e){const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-9999px",n.style.top="-9999px",document.body.appendChild(n),n.focus(),n.select();try{document.execCommand("copy"),e()}catch(t){}n.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=>Pt(this,void 0,void 0,function*(){var e;const n=t.target;if(n.files&&n.files.length>0){const t=Array.from(n.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 Pt(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(),n=this.urlInput.split("/").pop()||"downloaded-file",i=new File([e],n,{type:e.type});this.selectedUrlFileName=n,this.controller&&(yield this.controller.uploadFiles([i])),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)}handleFilePreview(t){this.previewFile=t,this.isFilePreviewModalOpen=!0}handleArtifactClick(t){if(!this.enableArtifacts||!this.controller)return;const e=this.getArtifactPlugin();if(!e)return;const n=e.getArtifact(t);n&&(this.selectedArtifact=n,this.isArtifactPanelOpen=!0)}handleArtifactPanelClose(){this.isArtifactPanelOpen=!1,this.selectedArtifact=null}updateArtifactPanelResize(){var t,e,n;const i=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(!i||!o)return null===(n=this._artifactResizeCleanup)||void 0===n||n.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,n=o.parentElement,i=n?.85*n.getBoundingClientRect().width:1200,l=Number.parseInt(getComputedStyle(o).minWidth,10)||300,c=Math.max(l,Math.min(a-e,i));o.style.width=`${c}px`},c=()=>{s&&(s=!1,i.classList.remove("artifact-panel__resize-handle--active"),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c))},d=t=>{t.preventDefault(),s=!0,r=t.clientX,a=o.getBoundingClientRect().width,i.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",c)};i.addEventListener("mousedown",d),this._artifactResizeCleanup=()=>{i.removeEventListener("mousedown",d),c()}}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 i=t.renderArtifactContent(e);if(i)return n`${l(i)}`};return}catch(t){return}}handleFilePreviewModalClose(){this.isFilePreviewModalOpen=!1,this.previewFile=null}addMessage(t){var e;const n=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(n),this.chatStarted=!0,n}clearMessages(){this.messages=[],this.chatStarted=!1}};Mt.useShadowDom=!0,Mt.styles=D,St([o({type:Array})],Mt.prototype,"messages",void 0),St([o({type:String})],Mt.prototype,"currentInput",void 0),St([o({type:Boolean})],Mt.prototype,"isBotTyping",void 0),St([o({type:Boolean})],Mt.prototype,"isQueryRunning",void 0),St([o({type:Array})],Mt.prototype,"suggestions",void 0),St([o({type:Boolean})],Mt.prototype,"chatStarted",void 0),St([o({type:Boolean})],Mt.prototype,"isRTL",void 0),St([o({type:String})],Mt.prototype,"size",void 0),St([o({type:String})],Mt.prototype,"variant",void 0),St([o({type:String})],Mt.prototype,"loadingIndicator",void 0),St([o({type:String})],Mt.prototype,"loadingText",void 0),St([o({type:Boolean})],Mt.prototype,"disabled",void 0),St([o({type:String})],Mt.prototype,"placeholder",void 0),St([o({type:Boolean})],Mt.prototype,"showSendButton",void 0),St([o({type:Boolean})],Mt.prototype,"autoScroll",void 0),St([o({type:Boolean})],Mt.prototype,"showThreads",void 0),St([o({type:Boolean})],Mt.prototype,"enableThreadCreation",void 0),St([o({type:Array})],Mt.prototype,"threads",void 0),St([o({type:String})],Mt.prototype,"activeThreadId",void 0),St([o({type:String})],Mt.prototype,"mode",void 0),St([o({type:Boolean,reflect:!0})],Mt.prototype,"boxed",void 0),St([o({type:Boolean})],Mt.prototype,"enableUrlSync",void 0),St([o({type:Boolean})],Mt.prototype,"showMessages",void 0),St([o({type:Boolean})],Mt.prototype,"enableFileUpload",void 0),St([o({type:Array})],Mt.prototype,"uploadedFiles",void 0),St([o({type:Array})],Mt.prototype,"actionButtons",void 0),St([o({type:Boolean})],Mt.prototype,"enableModuleSelection",void 0),St([o({type:Array})],Mt.prototype,"modules",void 0),St([o({type:Array})],Mt.prototype,"selectedModules",void 0),St([o({type:String})],Mt.prototype,"moduleSelectionLabel",void 0),St([o({type:Boolean})],Mt.prototype,"enableArtifacts",void 0),St([o({type:Boolean,attribute:"show-audio-button"})],Mt.prototype,"showAudioButton",void 0),St([o({type:Function})],Mt.prototype,"onAudioRecorded",void 0),St([o({type:Function})],Mt.prototype,"renderArtifactContent",void 0),St([o({type:Object})],Mt.prototype,"controller",void 0),St([s()],Mt.prototype,"statusText",void 0),St([s()],Mt.prototype,"focused",void 0),St([s()],Mt.prototype,"isArtifactPanelOpen",void 0),St([s()],Mt.prototype,"selectedArtifact",void 0),St([s()],Mt.prototype,"isThreadSidebarOpen",void 0),St([s()],Mt.prototype,"_editingThreadId",void 0),St([s()],Mt.prototype,"isUrlModalOpen",void 0),St([s()],Mt.prototype,"urlInput",void 0),St([s()],Mt.prototype,"urlModalError",void 0),St([s()],Mt.prototype,"isUrlLoading",void 0),St([s()],Mt.prototype,"selectedUrlFileName",void 0),St([s()],Mt.prototype,"isFilePreviewModalOpen",void 0),St([s()],Mt.prototype,"previewFile",void 0),Mt=St([(t,e)=>(t.addInitializer(b),t),r("nr-chatbot")],Mt);
|
|
2781
|
+
`}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)}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}};Et.useShadowDom=!0,Et.styles=F,Mt([o({type:Array})],Et.prototype,"messages",void 0),Mt([o({type:String})],Et.prototype,"currentInput",void 0),Mt([o({type:Boolean})],Et.prototype,"isBotTyping",void 0),Mt([o({type:Boolean})],Et.prototype,"isQueryRunning",void 0),Mt([o({type:Array})],Et.prototype,"suggestions",void 0),Mt([o({type:Boolean})],Et.prototype,"chatStarted",void 0),Mt([o({type:Boolean})],Et.prototype,"isRTL",void 0),Mt([o({type:String})],Et.prototype,"size",void 0),Mt([o({type:String})],Et.prototype,"variant",void 0),Mt([o({type:String})],Et.prototype,"loadingIndicator",void 0),Mt([o({type:String})],Et.prototype,"loadingText",void 0),Mt([o({type:Boolean})],Et.prototype,"disabled",void 0),Mt([o({type:String})],Et.prototype,"placeholder",void 0),Mt([o({type:Boolean})],Et.prototype,"showSendButton",void 0),Mt([o({type:Boolean})],Et.prototype,"autoScroll",void 0),Mt([o({type:Boolean})],Et.prototype,"showThreads",void 0),Mt([o({type:Boolean})],Et.prototype,"enableThreadCreation",void 0),Mt([o({type:Array})],Et.prototype,"threads",void 0),Mt([o({type:String})],Et.prototype,"activeThreadId",void 0),Mt([o({type:String})],Et.prototype,"mode",void 0),Mt([o({type:Boolean,reflect:!0})],Et.prototype,"boxed",void 0),Mt([o({type:Boolean})],Et.prototype,"enableUrlSync",void 0),Mt([o({type:Boolean})],Et.prototype,"showMessages",void 0),Mt([o({type:Boolean})],Et.prototype,"enableFileUpload",void 0),Mt([o({type:Array})],Et.prototype,"uploadedFiles",void 0),Mt([o({type:Array})],Et.prototype,"actionButtons",void 0),Mt([o({type:Boolean})],Et.prototype,"enableModuleSelection",void 0),Mt([o({type:Array})],Et.prototype,"modules",void 0),Mt([o({type:Array})],Et.prototype,"selectedModules",void 0),Mt([o({type:String})],Et.prototype,"moduleSelectionLabel",void 0),Mt([o({type:Boolean})],Et.prototype,"enableArtifacts",void 0),Mt([o({type:Boolean,attribute:"show-audio-button"})],Et.prototype,"showAudioButton",void 0),Mt([o({type:Function})],Et.prototype,"onAudioRecorded",void 0),Mt([o({type:Function})],Et.prototype,"renderArtifactContent",void 0),Mt([o({type:Object})],Et.prototype,"controller",void 0),Mt([s()],Et.prototype,"statusText",void 0),Mt([s()],Et.prototype,"focused",void 0),Mt([s()],Et.prototype,"isArtifactPanelOpen",void 0),Mt([s()],Et.prototype,"selectedArtifact",void 0),Mt([s()],Et.prototype,"isThreadSidebarOpen",void 0),Mt([s()],Et.prototype,"_editingThreadId",void 0),Mt([s()],Et.prototype,"isUrlModalOpen",void 0),Mt([s()],Et.prototype,"urlInput",void 0),Mt([s()],Et.prototype,"urlModalError",void 0),Mt([s()],Et.prototype,"isUrlLoading",void 0),Mt([s()],Et.prototype,"selectedUrlFileName",void 0),Mt([s()],Et.prototype,"isFilePreviewModalOpen",void 0),Mt([s()],Et.prototype,"previewFile",void 0),Et=Mt([(t,e)=>(t.addInitializer(b),t),r("nr-chatbot")],Et);
|
|
2624
2782
|
/**
|
|
2625
2783
|
* @license
|
|
2626
2784
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2627
2785
|
* SPDX-License-Identifier: MIT
|
|
2628
2786
|
*/
|
|
2629
|
-
class
|
|
2787
|
+
class Ct{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())}}
|
|
2630
2788
|
/**
|
|
2631
2789
|
* @license
|
|
2632
2790
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2633
2791
|
* SPDX-License-Identifier: MIT
|
|
2634
|
-
*/class
|
|
2792
|
+
*/class zt extends Error{constructor(t){super(t.join(", ")),this.errors=t,this.name="ValidationError"}}
|
|
2635
2793
|
/**
|
|
2636
2794
|
* @license
|
|
2637
2795
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2638
2796
|
* SPDX-License-Identifier: MIT
|
|
2639
|
-
*/class
|
|
2797
|
+
*/class Ot{constructor(t,e,i,n,o){this.eventBus=e,this.ui=i,this.plugins=n,this.config=o,this.state=t}getState(){return Object.freeze(Object.assign({},this.state))}updateState(t){if(this.state=Object.assign(Object.assign({},this.state),t),this.ui.onStateChange)try{this.ui.onStateChange(this.getState())}catch(t){this.logError("Error in UI state change callback:",t)}this.eventBus.emit("state:changed",this.state),this.plugins.forEach(t=>{if(t.onStateChange)try{t.onStateChange(this.getState())}catch(t){this.logError("Error in plugin state change handler:",t)}})}addMessageToState(t){this.state.messages=[...this.state.messages,t],t.suggestions&&t.suggestions.length>0?this.state.suggestions=[...t.suggestions]:this.state.messages.length>1&&(this.state.suggestions=[]),this.config.maxMessages&&this.state.messages.length>this.config.maxMessages&&(this.state.messages=this.state.messages.slice(-this.config.maxMessages)),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state),this.ui.scrollToBottom&&this.ui.scrollToBottom(),this.eventBus.emit("message:added",t)}updateMessageInState(t,e){this.state.messages=this.state.messages.map(i=>i.id===t?Object.assign(Object.assign({},i),e):i),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state);const i=this.state.messages.find(e=>e.id===t);i&&this.eventBus.emit("message:updated",i)}removeMessageFromState(t){this.state.messages=this.state.messages.filter(e=>e.id!==t),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state),this.eventBus.emit("message:deleted",t)}resetState(t){this.state=Object.assign({},t),this.updateState(this.state)}getMessages(){return[...this.state.messages]}getMessageById(t){return this.state.messages.find(e=>e.id===t)}isTyping(){return this.state.isTyping}isProcessing(){return this.state.isProcessing}setTyping(t){this.updateState({isTyping:t}),t&&this.ui.onTypingStart?this.ui.onTypingStart():!t&&this.ui.onTypingEnd&&this.ui.onTypingEnd()}setProcessing(t){this.updateState({isProcessing:t})}logError(t,e){console.error(`[StateHandler] ${t}`,e)}}
|
|
2640
2798
|
/**
|
|
2641
2799
|
* @license
|
|
2642
2800
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2643
2801
|
* SPDX-License-Identifier: MIT
|
|
2644
|
-
*/class
|
|
2802
|
+
*/class It{constructor(t,e,i){this.stateHandler=t,this.eventBus=e,this.plugins=i}createMessage(t){return Object.assign({id:this.generateId("msg"),sender:t.sender||"user",text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t)}createUserMessage(t,e){return this.createMessage({sender:"user",text:t,metadata:e})}createBotMessage(t,e){return this.createMessage({sender:"bot",text:t,metadata:e})}addMessage(t){const e=this.createMessage(t);return this.stateHandler.addMessageToState(e),"bot"===e.sender?(this.eventBus.emit("message:received",e),this.plugins.forEach(t=>{t.onMessageReceived&&t.onMessageReceived(e)})):(this.eventBus.emit("message:sent",e),this.plugins.forEach(t=>{t.onMessageSent&&t.onMessageSent(e)})),e}updateMessage(t,e){this.stateHandler.updateMessageInState(t,e)}deleteMessage(t){this.stateHandler.removeMessageFromState(t)}clearMessages(){this.stateHandler.updateState({messages:[]})}getMessages(){return this.stateHandler.getMessages()}getMessageById(t){return this.stateHandler.getMessageById(t)}updateBotMessageText(t,e){const i=this.getMessageById(t);i&&"bot"===i.sender&&this.updateMessage(t,{text:e})}appendToBotMessage(t,e){const i=this.getMessageById(t);i&&"bot"===i.sender&&this.updateMessage(t,{text:i.text+e})}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}
|
|
2645
2803
|
/**
|
|
2646
2804
|
* @license
|
|
2647
2805
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2648
2806
|
* SPDX-License-Identifier: MIT
|
|
2649
|
-
*/var
|
|
2807
|
+
*/var Rt=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 At{constructor(t,e,i,n,o){this.stateHandler=t,this.eventBus=e,this.ui=i,this.config=n,this.provider=o}setProvider(t){this.provider=t}createThread(t){return Rt(this,void 0,void 0,function*(){if(!this.config.enableThreads)throw new Error("Threads are not enabled");const e=this.stateHandler.getState(),i={id:this.generateId("thread"),title:t||`Chat ${e.threads.length+1}`,messages:[],createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()};if(this.provider&&"function"==typeof this.provider.createConversation)try{const t=yield this.provider.createConversation(i.title);t&&t.id&&(i.id=String(t.id),i.conversationId=t.id)}catch(t){console.error("Error calling provider.createConversation:",t)}return this.stateHandler.updateState({threads:[i,...e.threads],currentThreadId:i.id,messages:[]}),this.eventBus.emit("thread:created",i),this.eventBus.emit("thread:selected",i),this.ui.focusInput&&setTimeout(()=>{this.ui.focusInput()},100),i})}switchThread(t){const e=this.stateHandler.getState(),i=e.threads.find(e=>e.id===t);if(!i)throw new Error(`Thread "${t}" not found`);e.currentThreadId&&this.saveCurrentThread(),this.stateHandler.updateState({currentThreadId:t,messages:[...i.messages]}),this.eventBus.emit("thread:selected",i)}bookmarkThread(t){const e=this.stateHandler.getState(),i=e.threads.find(e=>e.id===t);if(!i)throw new Error(`Thread "${t}" not found`);const n=!i.bookmarked,o=e.threads.map(e=>e.id===t?Object.assign(Object.assign({},e),{bookmarked:n}):e);this.stateHandler.updateState({threads:o}),this.eventBus.emit("thread:bookmarked",{threadId:t,bookmarked:n})}renameThread(t,e){const i=this.stateHandler.getState();if(!i.threads.find(e=>e.id===t))throw new Error(`Thread "${t}" not found`);const n=i.threads.map(i=>i.id===t?Object.assign(Object.assign({},i),{title:e,updatedAt:(new Date).toISOString()}):i);this.stateHandler.updateState({threads:n}),this.eventBus.emit("thread:renamed",{threadId:t,title:e})}deleteThread(t){const e=this.stateHandler.getState(),i=e.threads.filter(e=>e.id!==t);e.currentThreadId===t?i.length>0?(this.stateHandler.updateState({threads:i}),this.switchThread(i[0].id)):this.stateHandler.updateState({threads:i,currentThreadId:void 0,messages:[]}):this.stateHandler.updateState({threads:i}),this.eventBus.emit("thread:deleted",t)}getCurrentThread(){const t=this.stateHandler.getState();return t.threads.find(e=>e.id===t.currentThreadId)}getThreads(){return[...this.stateHandler.getState().threads]}saveCurrentThread(){const t=this.stateHandler.getState();t.currentThreadId&&this.updateThreadMessages(t.currentThreadId)}updateThreadMessages(t){const e=this.stateHandler.getState(),i=e.threads.map(i=>i.id===t?Object.assign(Object.assign({},i),{messages:[...e.messages],updatedAt:(new Date).toISOString()}):i);this.stateHandler.updateState({threads:i})}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}
|
|
2650
2808
|
/**
|
|
2651
2809
|
* @license
|
|
2652
2810
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2653
2811
|
* SPDX-License-Identifier: MIT
|
|
2654
|
-
*/var
|
|
2812
|
+
*/var jt=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 Ft{constructor(t,e){this.stateHandler=t,this.eventBus=e}addFile(t){const e=this.stateHandler.getState();this.stateHandler.updateState({uploadedFiles:[...e.uploadedFiles,t]}),this.eventBus.emit("file:uploaded",t)}updateFile(t,e){const i=this.stateHandler.getState();this.stateHandler.updateState({uploadedFiles:i.uploadedFiles.map(i=>i.id===t?Object.assign(Object.assign({},i),e):i)})}removeFile(t){const e=this.stateHandler.getState(),i=e.uploadedFiles.find(e=>e.id===t);this.revokePreviewUrl(i),this.stateHandler.updateState({uploadedFiles:e.uploadedFiles.filter(e=>e.id!==t)}),this.eventBus.emit("file:removed",t)}revokePreviewUrl(t){if(t&&t.previewUrl&&"undefined"!=typeof URL&&URL.revokeObjectURL&&t.previewUrl.startsWith("blob:"))try{URL.revokeObjectURL(t.previewUrl)}catch(t){}}clearFiles(){this.stateHandler.updateState({uploadedFiles:[]})}getUploadedFiles(){return[...this.stateHandler.getState().uploadedFiles]}getFileById(t){return this.stateHandler.getState().uploadedFiles.find(e=>e.id===t)}createChatbotFile(t){return jt(this,void 0,void 0,function*(){const e={id:this.generateId("file"),name:t.name,size:t.size,type:this.determineFileType(t.type),mimeType:t.type,uploadProgress:0,isUploading:!0};if(t.type.startsWith("image/")&&"undefined"!=typeof URL&&URL.createObjectURL)try{e.previewUrl=URL.createObjectURL(t)}catch(t){}return e})}determineFileType(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t.includes("pdf")?"pdf":t.includes("text/")?"text":"document"}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}
|
|
2655
2813
|
/**
|
|
2656
2814
|
* @license
|
|
2657
2815
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2658
2816
|
* SPDX-License-Identifier: MIT
|
|
2659
|
-
*/class
|
|
2817
|
+
*/class Dt{constructor(t,e){this.stateHandler=t,this.eventBus=e}setModules(t){this.stateHandler.updateState({modules:t})}selectModules(t){this.stateHandler.updateState({selectedModules:t}),this.eventBus.emit("module:selected",t)}toggleModule(t){const e=this.stateHandler.getState(),i=e.selectedModules.includes(t)?e.selectedModules.filter(e=>e!==t):[...e.selectedModules,t];this.selectModules(i)}getSelectedModules(){const t=this.stateHandler.getState();return(t.modules||[]).filter(e=>t.selectedModules.includes(e.id))}clearSelection(){this.stateHandler.updateState({selectedModules:[]})}}
|
|
2660
2818
|
/**
|
|
2661
2819
|
* @license
|
|
2662
2820
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2663
2821
|
* SPDX-License-Identifier: MIT
|
|
2664
|
-
*/class
|
|
2822
|
+
*/class Nt{constructor(t){this.stateHandler=t}setSuggestions(t){this.stateHandler.updateState({suggestions:t})}clearSuggestions(){this.stateHandler.updateState({suggestions:[]})}getSuggestions(){return[...this.stateHandler.getState().suggestions]}removeSuggestion(t){const e=this.stateHandler.getState();this.stateHandler.updateState({suggestions:e.suggestions.filter(e=>e.id!==t)})}}
|
|
2665
2823
|
/**
|
|
2666
2824
|
* @license
|
|
2667
2825
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2668
2826
|
* SPDX-License-Identifier: MIT
|
|
2669
|
-
*/var
|
|
2827
|
+
*/var Lt=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 Bt{constructor(t,e,i,n,o,s,r){this.stateHandler=e,this.messageHandler=i,this.fileHandler=n,this.eventBus=o,this.ui=s,this.plugins=r,this.cancelRequested=!1,this.provider=t}setProvider(t){this.provider=t}stopCurrentProcessing(){this.cancelRequested=!0,this.eventBus.emit("processing:stopped")}hasProvider(){return!!this.provider&&this.provider.isConnected()}processMessage(t){return Lt(this,void 0,void 0,function*(){if(this.provider){if(!this.provider.isConnected()){this.log("Provider not connected, attempting to connect...");try{yield this.provider.connect({})}catch(t){this.logError("Failed to auto-connect provider:",t)}if(!this.provider.isConnected())return void this.log("Provider is still not connected after attempt; aborting processing")}try{this.cancelRequested=!1,this.ui.onProcessingStart&&this.ui.onProcessingStart(),this.ui.onTypingStart&&this.ui.onTypingStart(),this.stateHandler.setTyping(!0),this.stateHandler.setProcessing(!0),this.eventBus.emit("processing:start");const e=this.buildContext(),i=this.provider.sendMessage(t.text,e);yield this.processStream(i)}catch(t){throw this.logError("Provider error:",t),this.eventBus.emit("error",t),t}finally{this.ui.onProcessingEnd&&this.ui.onProcessingEnd(),this.ui.onTypingEnd&&this.ui.onTypingEnd(),this.stateHandler.updateState({statusText:void 0}),this.stateHandler.setTyping(!1),this.stateHandler.setProcessing(!1),this.eventBus.emit("processing:end"),this.fileHandler.clearFiles()}}else this.log("No provider configured")})}processStream(t){return Lt(this,void 0,void 0,function*(){var e;let i=null;const n=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)),o=[];let s="",r="",a=0;if(n.length>0)for(const t of n)for(const e of t.htmlTags)a=Math.max(a,e.open.length,e.close.length);try{let l=!1;for(;!l&&!this.cancelRequested;){const d=yield t.next();if(l=d.done||!1,l||!d.value)break;const c=String(d.value),h=c.startsWith(r)?c.slice(r.length):c;r=c,s+=h;let u="",p=!1;for(;s.length;){const t=o[o.length-1];if(t){const e=t.buffer+s,n=e.indexOf(t.close);if(-1===n){t.buffer=e,s="";break}const r=e.slice(0,n),a="function"==typeof t.plugin.renderHtmlBlock?t.plugin.renderHtmlBlock(t.name,r):"";if(a)if(t.hasPlaceholder&&i){const t=/<div data-placeholder-id="[^"]*">[\s\S]*?<\/div>/;t.test(i.text)?(i.text=i.text.replace(t,a),this.messageHandler.updateMessage(i.id,{text:i.text})):(u+=a,p=!0)}else u+=a,p=!0;o.pop(),s=e.slice(n+t.close.length);continue}if(0===n.length){u+=s,s="";break}let e=null;for(const t of n)for(const i of t.htmlTags){const n=s.indexOf(i.open);-1!==n&&(!e||n<e.idx)&&(e={idx:n,plugin:t,name:i.name,open:i.open,close:i.close})}if(!e){if(a>0&&s.length>a-1){const t=s.length-(a-1);u+=s.slice(0,t),s=s.slice(t)}break}{u+=s.slice(0,e.idx);let t=!1;if("function"==typeof e.plugin.renderHtmlBlockPlaceholder){const i=e.plugin.renderHtmlBlockPlaceholder(e.name);i&&(u+=i,p=!0,t=!0)}o.push({plugin:e.plugin,name:e.name,open:e.open,close:e.close,buffer:"",hasPlaceholder:t}),s=s.slice(e.idx+e.open.length)}}if(u)for(const t of this.plugins.values()){!(Array.isArray(t.htmlTags)&&t.htmlTags.length>0)&&t.afterReceive&&(u=yield t.afterReceive(u))}const f=p||/<\w+[^>]*>/.test(u);i?u&&(this.messageHandler.appendToBotMessage(i.id,u),i.text+=u,f&&!(null===(e=i.metadata)||void 0===e?void 0:e.renderAsHtml)&&this.messageHandler.updateMessage(i.id,{metadata:Object.assign(Object.assign({},i.metadata||{}),{renderAsHtml:!0})})):(i=this.messageHandler.createBotMessage(u,f?{renderAsHtml:!0}:void 0),this.stateHandler.addMessageToState(i),this.ui.onTypingEnd&&this.ui.onTypingEnd(),this.stateHandler.setTyping(!1))}if(!this.cancelRequested&&i&&(s&&this.messageHandler.appendToBotMessage(i.id,s),o.length>0)){const t=o.map(t=>t.open+t.buffer).join("");t&&this.messageHandler.appendToBotMessage(i.id,t)}}catch(t){throw this.logError("Error processing stream:",t),t}})}buildContext(){const t=this.stateHandler.getState(),e=t.currentThreadId?t.threads.find(e=>e.id===t.currentThreadId):void 0;return console.log("[ProviderService] buildContext state.uploadedFiles:",t.uploadedFiles),{messages:t.messages,metadata:t.metadata,selectedModules:t.selectedModules,currentThread:e,uploadedFiles:t.uploadedFiles}}uploadFileToProvider(t){return Lt(this,void 0,void 0,function*(){var e,i;if(!(null===(i=null===(e=this.provider)||void 0===e?void 0:e.capabilities)||void 0===i?void 0:i.fileUpload)||!this.provider.uploadFile)throw new Error("Provider does not support file upload");const n=this.buildContext();return yield this.provider.uploadFile(t,n)})}getCapabilities(){var t;return(null===(t=this.provider)||void 0===t?void 0:t.capabilities)||{streaming:!1,fileUpload:!1,contextWindow:0}}log(t,...e){console.log(`[ProviderService] ${t}`,...e)}logError(t,e){console.error(`[ProviderService] ${t}`,e)}}
|
|
2670
2828
|
/**
|
|
2671
2829
|
* @license
|
|
2672
2830
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2673
2831
|
* SPDX-License-Identifier: MIT
|
|
2674
|
-
*/var
|
|
2832
|
+
*/var Ut=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 Wt{constructor(t){this.validators=[],this.validators=t.validators||[]}validateMessage(t){return Ut(this,void 0,void 0,function*(){const e=[],i=[];t.trim()||e.push("Message cannot be empty");for(const n of this.validators)try{(yield n.validator(t))||(e.push(n.errorMessage),n.warningMessage&&i.push(n.warningMessage))}catch(t){this.logError("Validation error:",t),e.push("Validation failed")}return{isValid:0===e.length,errors:e,warnings:i}})}validateFile(t,e){const i=[],n=(null==e?void 0:e.maxFileSize)||10485760;if(t.size>n&&i.push(`File size exceeds maximum allowed (${this.formatFileSize(n)})`),(null==e?void 0:e.allowedTypes)&&e.allowedTypes.length>0){e.allowedTypes.some(e=>e.startsWith(".")?t.name.toLowerCase().endsWith(e.toLowerCase()):t.type.includes(e))||i.push(`File type not allowed. Allowed types: ${e.allowedTypes.join(", ")}`)}return{isValid:0===i.length,errors:i,warnings:[]}}addValidator(t){this.validators.push(t)}removeValidator(t){this.validators=this.validators.filter(e=>e.id!==t)}clearValidators(){this.validators=[]}getValidators(){return[...this.validators]}formatFileSize(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,e)*100)/100+" "+["Bytes","KB","MB","GB"][e]}logError(t,e){console.error(`[ValidationService] ${t}`,e)}}
|
|
2675
2833
|
/**
|
|
2676
2834
|
* @license
|
|
2677
2835
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2678
2836
|
* SPDX-License-Identifier: MIT
|
|
2679
|
-
*/var
|
|
2837
|
+
*/var Ht=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 Jt{constructor(t,e,i){this.stateHandler=e,this.config=i,this.storage=t,this.setupAutoSave()}setStorage(t){this.storage=t,this.setupAutoSave()}saveState(){return Ht(this,arguments,void 0,function*(t="chatbot-state"){if(!this.storage)throw new Error("No storage configured");try{const e=this.stateHandler.getState();yield this.storage.save(t,e),this.log("State saved to storage")}catch(t){throw this.logError("Error saving to storage:",t),t}})}loadState(){return Ht(this,arguments,void 0,function*(t="chatbot-state"){if(!this.storage)throw new Error("No storage configured");try{const e=yield this.storage.load(t);e&&(this.stateHandler.updateState(e),this.log("State loaded from storage"))}catch(t){throw this.logError("Error loading from storage:",t),t}})}clearStorage(){return Ht(this,void 0,void 0,function*(){if(!this.storage)throw new Error("No storage configured");try{yield this.storage.clear(),this.log("Storage cleared")}catch(t){throw this.logError("Error clearing storage:",t),t}})}setupAutoSave(){this.autoSaveTimer&&clearInterval(this.autoSaveTimer),this.config.autoSaveInterval&&this.storage&&(this.autoSaveTimer=setInterval(()=>{this.saveState().catch(t=>{this.logError("Auto-save failed:",t)})},this.config.autoSaveInterval))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=void 0)}startAutoSave(t){this.config.autoSaveInterval=t,this.setupAutoSave()}hasStorage(){return!!this.storage}destroy(){this.stopAutoSave()}log(t){console.log(`[StorageService] ${t}`)}logError(t,e){console.error(`[StorageService] ${t}`,e)}}
|
|
2680
2838
|
/**
|
|
2681
2839
|
* @license
|
|
2682
2840
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2683
2841
|
* SPDX-License-Identifier: MIT
|
|
2684
|
-
*/var
|
|
2842
|
+
*/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 Vt{constructor(t){this.plugins=new Map,t&&t.forEach(t=>this.registerPlugin(t))}registerPlugin(t,e){if(this.plugins.has(t.id))this.log(`Plugin "${t.id}" is already registered, skipping`);else if(this.plugins.set(t.id,t),this.log(`Registered plugin: ${t.name} v${t.version}`),t.onInit&&e)try{t.onInit(e)}catch(e){this.logError(`Error initializing plugin "${t.id}":`,e)}}unregisterPlugin(t){const e=this.plugins.get(t);if(e&&e.onDestroy)try{e.onDestroy()}catch(e){this.logError(`Error destroying plugin "${t}":`,e)}this.plugins.delete(t),this.log(`Unregistered plugin: ${t}`)}getPlugin(t){return this.plugins.get(t)}getAllPlugins(){return Array.from(this.plugins.values())}hasPlugin(t){return this.plugins.has(t)}getPluginsMap(){return this.plugins}executeHook(t,...e){return qt(this,void 0,void 0,function*(){for(const i of this.plugins.values()){const n=i[t];if("function"==typeof n)try{yield n(...e)}catch(e){this.logError(`Error executing hook "${String(t)}" on plugin "${i.id}":`,e)}}})}clearPlugins(){this.plugins.forEach((t,e)=>{this.unregisterPlugin(e)}),this.plugins.clear()}getPluginCount(){return this.plugins.size}log(t){console.log(`[PluginService] ${t}`)}logError(t,e){console.error(`[PluginService] ${t}`,e)}}const Gt=["ar","fr"],Kt="__nuraly_localization__";!function(){if(globalThis[Kt])return globalThis[Kt];const t=R({sourceLocale:"en",targetLocales:Gt,loadLocale:t=>import(`../../locales/generated/${t}.js`)});globalThis[Kt]=t}();
|
|
2685
2843
|
/**
|
|
2686
2844
|
* @license
|
|
2687
2845
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2688
2846
|
* SPDX-License-Identifier: MIT
|
|
2689
2847
|
*/
|
|
2690
|
-
var Gt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Kt{constructor(t={}){this.plugins=new Map,this.config=t,this.ui=t.ui||{},this.eventBus=new Tt,this.pluginService=new Jt,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 Ct(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new zt(this.stateHandler,this.eventBus,this.plugins),this.threadHandler=new It(this.stateHandler,this.eventBus,this.ui,this.config,t.provider),this.fileHandler=new At(this.stateHandler,this.eventBus),this.moduleHandler=new jt(this.stateHandler,this.eventBus),this.suggestionHandler=new Dt(this.stateHandler),this.providerService=new Nt(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new Lt(this.config),this.storageService=new Wt(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Gt(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 n=t.text,i=!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=n.indexOf(e,r);if(-1===a)break;const l=a+e.length,c=n.indexOf(s,l);if(-1===c){r=l;continue}const d=n.substring(l,c);let h="";if("function"==typeof t.renderHtmlBlock)try{h=t.renderHtmlBlock(o.name,d)}catch(e){console.error(`[ChatbotCore] Error rendering HTML block for plugin ${t.id}:`,e)}h?(n=n.substring(0,a)+h+n.substring(c+s.length),i=!0,r=a+h.length):r=c+s.length}}}return i?Object.assign(Object.assign({},t),{text:n,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 Gt(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 Gt(this,arguments,void 0,function*(t,e={}){this.log("Sending message:",t);try{const n=this.stateHandler.getState();this.config.enableThreads&&!n.currentThreadId&&(yield this.threadHandler.createThread("New Chat"));const i=yield this.beforeMessageSent(t,e);if(!e.skipValidation){const t=yield this.validationService.validateMessage(i);if(!t.isValid){const e=new Et(t.errors);throw this.handleValidationError(e),e}}const o=this.messageHandler.createUserMessage(i,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),n="bot"===e.sender?this.processMessageThroughPlugins(e):e;return this.messageHandler.addMessage(n),n}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 Gt(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 n=[];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 i=yield this.fileHandler.createChatbotFile(t),o=yield this.providerService.uploadFileToProvider(t);o&&Object.assign(i,o),n.push(i),this.fileHandler.addFile(i),this.ui.showFilePreview&&this.ui.showFilePreview(i)}catch(e){this.logError("Error uploading file:",e),this.ui.showNotification&&this.ui.showNotification(`Failed to upload ${t.name}`,"error")}return n})}removeFile(t){this.fileHandler.removeFile(t)}clearFiles(){this.fileHandler.clearFiles()}getUploadedFiles(){return this.stateHandler.getState().uploadedFiles}createThread(t){return Gt(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 Gt(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 Gt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Gt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Gt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Gt(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(()=>Gt(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 Gt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Gt(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 Gt(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 n=[];if("function"==typeof t.loadConversation)for(const i of e)try{const e=yield t.loadConversation(i.id);if(e){const t={id:e.id,title:e.title,messages:e.messages||[],createdAt:e.createdAt,updatedAt:e.updatedAt};n.push(t)}}catch(t){this.logError(`Failed to load conversation ${i.id}:`,t)}else for(const t of e){const e={id:t.id,title:t.title,messages:[],createdAt:t.createdAt,updatedAt:t.updatedAt};n.push(e)}n.length>0&&(this.log(`Successfully loaded ${n.length} conversations`),this.loadConversations(n))}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)}}
|
|
2848
|
+
var Yt=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 Ct,this.pluginService=new Vt,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 Ot(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new It(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 Nt(this.stateHandler),this.providerService=new Bt(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new Wt(this.config),this.storageService=new Jt(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Yt(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 Yt(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 Yt(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 Yt(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 Yt(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 Yt(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 Yt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Yt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Yt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Yt(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(()=>Yt(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 Yt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Yt(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 Yt(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)}}
|
|
2691
2849
|
/**
|
|
2692
2850
|
* @license
|
|
2693
2851
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2694
2852
|
* SPDX-License-Identifier: MIT
|
|
2695
|
-
*/var
|
|
2853
|
+
*/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())})},Zt=function(t){return this instanceof Zt?(this.v=t,this):new Zt(t)},te=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 Zt?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 ee{constructor(){this.id="openai",this.name="OpenAI",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!0,imageGeneration:!0},this.apiKey="",this.apiUrl="https://api.openai.com/v1",this.model="gpt-4",this.temperature=.7,this.connected=!1}connect(t){return Qt(this,void 0,void 0,function*(){var e;if(!t.apiKey)throw new Error("OpenAI API key is required");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl||this.apiUrl,this.model=t.model||this.model,this.temperature=null!==(e=t.temperature)&&void 0!==e?e:this.temperature,this.maxTokens=t.maxTokens;try{const t=yield fetch(`${this.apiUrl}/models`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!t.ok)throw new Error(`OpenAI connection failed: ${t.statusText}`);this.connected=!0,console.log("[OpenAIProvider] Connected successfully")}catch(t){throw this.connected=!1,t}})}disconnect(){return Qt(this,void 0,void 0,function*(){this.connected=!1,console.log("[OpenAIProvider] Disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return te(this,arguments,function*(){var i,n,o;if(!this.connected)throw new Error("Provider not connected");const s=this.buildMessages(t,e),r=yield Zt(fetch(`${this.apiUrl}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:s,temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})}));if(!r.ok)throw new Error(`OpenAI API error: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");const a=r.body.getReader(),l=new TextDecoder;let d="";try{for(;;){const{done:t,value:e}=yield Zt(a.read());if(t)break;d+=l.decode(e,{stream:!0});const s=d.split("\n");d=s.pop()||"";for(const t of s)if(""!==t.trim()&&"data: [DONE]"!==t.trim()&&t.startsWith("data: ")){const e=t.slice(6);try{const t=null===(o=null===(n=null===(i=JSON.parse(e).choices)||void 0===i?void 0:i[0])||void 0===n?void 0:n.delta)||void 0===o?void 0:o.content;t&&(yield yield Zt(t))}catch(t){console.error("Error parsing SSE data:",t)}}}}finally{a.releaseLock()}})}getAvailableModules(){return Qt(this,void 0,void 0,function*(){return[{id:"web-search",name:"Web Search",description:"Search the web for information",icon:"search",enabled:!0},{id:"code-interpreter",name:"Code Interpreter",description:"Execute Python code",icon:"code",enabled:!0},{id:"dalle",name:"DALL-E",description:"Generate images",icon:"image",enabled:!0}]})}callModule(t,e){return Qt(this,void 0,void 0,function*(){return console.log(`[OpenAIProvider] Calling module: ${t}`,e),{success:!0,result:"Module executed"}})}uploadFile(t){return Qt(this,void 0,void 0,function*(){const e=new FormData;e.append("file",t),e.append("purpose","assistants");const i=yield fetch(`${this.apiUrl}/files`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:e});if(!i.ok)throw new Error(`File upload failed: ${i.statusText}`);const n=yield i.json();return{id:n.id,name:t.name,size:t.size,type:this.determineFileType(t.type),mimeType:t.type,url:n.url}})}onError(t){console.error("[OpenAIProvider] Error:",t)}buildMessages(t,e){const i=[],n=e.messages.slice(-10);for(const t of n)i.push({role:"user"===t.sender?"user":"assistant",content:t.text});return i.find(e=>"user"===e.role&&e.content===t)||i.push({role:"user",content:t}),i}determineFileType(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"document"}}
|
|
2696
2854
|
/**
|
|
2697
2855
|
* @license
|
|
2698
2856
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2699
2857
|
* SPDX-License-Identifier: MIT
|
|
2700
|
-
*/var
|
|
2858
|
+
*/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())})},ne=function(t){return this instanceof ne?(this.v=t,this):new ne(t)},oe=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 ne?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 se{constructor(){this.id="custom-api",this.name="Custom API",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.apiUrl="",this.headers={},this.connected=!1}connect(t){return ie(this,void 0,void 0,function*(){if(!t.apiUrl)throw new Error("API URL is required");this.apiUrl=t.apiUrl,this.headers=Object.assign({},t.headers),this.headers["Content-Type"]||(this.headers["Content-Type"]="application/json"),t.apiKey&&(this.headers.Authorization=`Bearer ${t.apiKey}`),this.connected=!0,console.log("[CustomAPIProvider] Connected")})}disconnect(){return ie(this,void 0,void 0,function*(){this.connected=!1,console.log("[CustomAPIProvider] Disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return oe(this,arguments,function*(){var i;if(!this.connected)return yield yield ne(this.formatError("Provider not connected","Please check your connection settings.")),yield ne(void 0);try{const n=this.buildPayload(t,e);let o,s;if(!(null===(i=this.headers["Content-Type"])||void 0===i?void 0:i.includes("multipart/form-data"))||"object"!=typeof n||n instanceof FormData)n instanceof FormData?(o=n,s=Object.assign({},this.headers),delete s["Content-Type"]):(o=JSON.stringify(n),s=this.headers);else{const t=new FormData;for(const[e,i]of Object.entries(n))null!=i&&t.append(e,"object"==typeof i?JSON.stringify(i):String(i));o=t,s=Object.assign({},this.headers),delete s["Content-Type"]}const r=yield ne(fetch(this.apiUrl,{method:"POST",headers:s,body:o}));if(!r.ok){const t=yield ne(r.text().catch(()=>r.statusText));return yield yield ne(this.formatError(`${r.status} ${r.statusText}`,t||"The server returned an error. Please try again.")),yield ne(void 0)}if(!r.body)return yield yield ne(this.formatError("Response Error","The server response body is empty.")),yield ne(void 0);const a=r.headers.get("content-type");if((null==a?void 0:a.includes("text/event-stream"))||(null==a?void 0:a.includes("stream"))||(null==a?void 0:a.includes("text/plain"))){const t=this.handleStreamResponse(r);let e=yield ne(t.next());for(;!e.done;)yield yield ne(e.value),e=yield ne(t.next())}else try{const t=yield ne(r.json());yield yield ne(this.extractMessage(t))}catch(t){yield yield ne(this.formatError("Parse Error","Failed to parse the server response."))}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ne(this.formatError("Network Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}handleStreamResponse(t){return oe(this,arguments,function*(){const e=t.body.getReader(),i=new TextDecoder;let n="";try{for(;;){const{done:t,value:o}=yield ne(e.read());if(t)break;n+=i.decode(o,{stream:!0}),yield yield ne(n)}n.length>0&&(yield yield ne(n))}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ne("\n\n"+this.formatError("Streaming Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}finally{e.releaseLock()}})}buildPayload(t,e){return{userMessage:t,variables:e.metadata||{},stream:!0}}extractMessage(t){return t.message||t.text||t.response||JSON.stringify(t)}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[CustomAPIProvider] Error:",t)}}
|
|
2701
2859
|
/**
|
|
2702
2860
|
* @license
|
|
2703
2861
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2704
2862
|
* SPDX-License-Identifier: MIT
|
|
2705
|
-
*/var
|
|
2863
|
+
*/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())})},ae=function(t){return this instanceof ae?(this.v=t,this):new ae(t)},le=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,i=t[Symbol.asyncIterator];return i?i.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(i){e[i]=t[i]&&function(e){return new Promise(function(n,o){(function(t,e,i,n){Promise.resolve(n).then(function(e){t({value:e,done:i})},e)})(n,o,(e=t[i](e)).done,e.value)})}}},de=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 ae?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 ce=["That's an interesting question! Let me think about that...","I understand what you're asking. Here's what I think:","Great point! Based on what you've told me, I would suggest:","I'd be happy to help with that. Let me explain:","That's a common question. The answer is:","I see where you're coming from. Let me clarify:","Excellent question! Here's my perspective:","I can definitely help you with that. Consider this:"],he={hello:["Hello! 👋 How can I help you today?","Hi there! What can I do for you?","Hey! Great to see you. What's on your mind?"],help:["I'm here to help! You can ask me anything. Try asking about features, getting started, or technical questions.","I can assist with various topics. What do you need help with?","Sure! I'm ready to help. What would you like to know?"],bye:["Goodbye! Feel free to come back anytime! 👋","See you later! Have a great day!","Bye! It was nice chatting with you!"],thanks:["You're welcome! Happy to help! 😊","Glad I could help!","Anytime! That's what I'm here for!"],how:["Great question! Here's how it works: First, you need to understand the basics. Then, you can dive deeper into the specifics.","Let me explain the process step by step...","That's actually quite straightforward. Let me break it down for you:"],what:["Good question! Let me explain what that means...","That refers to a concept that's important to understand. Here's the breakdown:","Interesting topic! Here's what you need to know:"],why:["That's because of several factors. Let me explain the reasoning:","Great question! The main reason is that it provides better functionality and user experience.","There are multiple reasons for this. The primary one is:"]};class ue{constructor(t={}){var e,i,n,o,s,r,a,l,d,c,h,u;this.id="mock-provider",this.name="Mock Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!1,functions:!0},this.messageCount=0,this.connected=!1,this.config={delay:null!==(e=t.delay)&&void 0!==e?e:800,streaming:null!==(i=t.streaming)&&void 0!==i&&i,streamingSpeed:null!==(n=t.streamingSpeed)&&void 0!==n?n:3,streamingInterval:null!==(o=t.streamingInterval)&&void 0!==o?o:50,contextualResponses:null===(s=t.contextualResponses)||void 0===s||s,echoMode:null!==(r=t.echoMode)&&void 0!==r&&r,customResponses:null!==(a=t.customResponses)&&void 0!==a?a:[],errorRate:null!==(l=t.errorRate)&&void 0!==l?l:0,useHistory:null===(d=t.useHistory)||void 0===d||d,simulateToolCalls:null!==(c=t.simulateToolCalls)&&void 0!==c&&c,toolCallNames:null!==(h=t.toolCallNames)&&void 0!==h?h:["search_web","get_weather","run_code"],toolCallDelay:null!==(u=t.toolCallDelay)&&void 0!==u?u:1500}}connect(t){return re(this,void 0,void 0,function*(){yield this.delay(100),this.connected=!0,console.log("🤖 Mock Provider connected")})}disconnect(){return re(this,void 0,void 0,function*(){this.connected=!1,console.log("🤖 Mock Provider disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return de(this,arguments,function*(){var i,n,o,s,r,a;if(this.messageCount++,Math.random()<this.config.errorRate)throw yield ae(this.delay(this.config.delay/2)),new Error("Simulated API error for testing");if(yield ae(this.delay(this.config.delay)),this.config.simulateToolCalls){const t=this.config.toolCallNames,e=1+Math.floor(Math.random()*Math.min(t.length,3));for(let i=0;i<e;i++){const e=t[i%t.length];null===(r=this.onToolCall)||void 0===r||r.call(this,e),yield ae(this.delay(this.config.toolCallDelay)),null===(a=this.onToolCallEnd)||void 0===a||a.call(this)}}const l=this.generateResponse(t,e);if(this.config.streaming)try{for(var d,c=!0,h=le(this.streamResponse(l));!(i=(d=yield ae(h.next())).done);c=!0){s=d.value,c=!1;const t=s;yield yield ae(t)}}catch(t){n={error:t}}finally{try{c||i||!(o=h.return)||(yield ae(o.call(h)))}finally{if(n)throw n.error}}else yield yield ae(l)})}uploadFile(t){return re(this,void 0,void 0,function*(){if(yield this.delay(this.config.delay),Math.random()<this.config.errorRate)throw new Error("Simulated file upload error for testing");const e=t.type||"application/octet-stream",i=this.determineFileType(e),n=`mock-file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;console.log(`📎 Mock Provider: File uploaded - ${t.name} (${t.size} bytes) - ID: ${n}`);return{id:n,name:t.name,size:t.size,type:i,mimeType:e,url:URL.createObjectURL(t),previewUrl:"image"===i?URL.createObjectURL(t):void 0,uploadProgress:100,metadata:{provider:"mock",uploadedAt:(new Date).toISOString()}}})}determineFileType(t){return t.startsWith("image/")?X.Image:t.startsWith("video/")?X.Video:t.startsWith("audio/")?X.Audio:t.startsWith("application/pdf")||t.includes("document")||t.includes("text")?X.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?X.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?X.Code:X.Unknown}generateResponse(t,e){var i,n;const o=(null==e?void 0:e.messages)||[],s=null===(i=[...o].map((t,e)=>({m:t,i:e})).reverse().find(({m:t})=>"user"===t.sender&&!!t.text))||void 0===i?void 0:i.i,r="number"==typeof s&&(null===(n=o[s])||void 0===n?void 0:n.text)?o[s].text:t;if(this.config.echoMode)return`You said: "${r}"`;if(this.config.customResponses.length>0){const t=(this.messageCount-1)%this.config.customResponses.length;return this.config.customResponses[t]}if(this.config.contextualResponses){const t=this.getContextualResponse(r);if(t)return t}if(this.config.useHistory&&o.length>0&&"number"==typeof s){const t=[...o].slice(0,s).reverse().find(t=>"user"===t.sender&&!!t.text);return t&&t.text?`Great point about "${String(r).substring(0,60)}". Considering your earlier message about "${String(t.text).substring(0,30)}...", ${this.getRandomResponse()}`:`Regarding "${String(r).substring(0,60)}", ${this.getRandomResponse()}`}return`Regarding "${String(r).substring(0,60)}", ${this.getRandomResponse()}`}getContextualResponse(t){const e=t.toLowerCase();for(const[t,i]of Object.entries(he))if(e.includes(t)){return i[Math.floor(Math.random()*i.length)]}return null}getRandomResponse(){const t=Math.floor(Math.random()*ce.length);return ce[t]}streamResponse(t){return de(this,arguments,function*(){let e="";const i=t.split(" ");for(let t=0;t<i.length;t++){e+=(t>0?" ":"")+i[t],yield yield ae(e),t<i.length-1&&(yield ae(this.delay(this.config.streamingInterval)))}})}delay(t){return new Promise(e=>setTimeout(e,t))}reset(){this.messageCount=0}updateConfig(t){Object.assign(this.config,t)}getConfig(){return Object.assign({},this.config)}}const pe={fast:()=>new ue({delay:300,streaming:!1,contextualResponses:!0}),realistic:()=>new ue({delay:1200,streaming:!0,streamingInterval:50,contextualResponses:!0,useHistory:!0}),slow:()=>new ue({delay:3e3,streaming:!1}),echo:()=>new ue({delay:500,echoMode:!0}),streaming:()=>new ue({delay:800,streaming:!0,streamingSpeed:2,streamingInterval:30}),unreliable:()=>new ue({delay:1e3,errorRate:.3}),custom:t=>new ue({delay:800,customResponses:t})};
|
|
2706
2864
|
/**
|
|
2707
2865
|
* @license
|
|
2708
2866
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2709
2867
|
* SPDX-License-Identifier: MIT
|
|
2710
|
-
*/var
|
|
2868
|
+
*/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())})},me=function(t){return this instanceof me?(this.v=t,this):new me(t)},ge=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 me?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 ve={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 be{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 fe(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({},ve),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 fe(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 ge(this,arguments,function*(){if(!this.connected||!this.socket||!this.config)return yield yield me(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield me(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 me(t);clearInterval(o),yield yield me(e)}catch(t){throw clearInterval(o),t}}else{const e=yield me(t);yield yield me(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield me(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)}}
|
|
2711
2869
|
/**
|
|
2712
2870
|
* @license
|
|
2713
2871
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2714
2872
|
* SPDX-License-Identifier: MIT
|
|
2715
|
-
*/var ve=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},be=function(t){return this instanceof be?(this.v=t,this):new be(t)},ye=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=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,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof be?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class xe{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 ve(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})},transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const n=setTimeout(()=>{e(new Error("Socket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(n),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(n),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 n,i,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===(i=null===(n=this.config)||void 0===n?void 0:n.onMessage)||void 0===i||i.call(n,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 n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0;let i="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)i=this.config.extractResponse(e);else if(n.messages.length>0)i=n.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;i=t.response||t.message||t.result||JSON.stringify(t)}catch(t){i=e.outputData}n.resolve(i||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,n=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,n),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0,i.reject(new Error(n)),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 ve(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 ye(this,arguments,function*(){var n,i;if(!this.connected||!this.socket||!this.config)return yield yield be(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield be(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 be(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield be(a.text().catch(()=>a.statusText));return yield yield be(this.formatError(`${a.status} ${a.statusText}`,t)),yield be(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(n=yield be(a.json().catch(()=>({}))))||void 0===n?void 0:n.executionId);if(!l)return yield yield be(this.formatError("Execution Error","No execution ID received from server")),yield be(void 0);console.log("[WorkflowSocketProvider] Execution started:",l),(null===(i=this.config)||void 0===i?void 0:i.onExecutionStart)&&this.config.onExecutionStart(l,this.config.workflowId),this.subscribeToExecution(l);const c=new Promise((t,e)=>{this.activeExecutions.set(l,{messages:[],resolve:t,reject:e,completed:!1}),setTimeout(()=>{const n=this.activeExecutions.get(l);n&&!n.completed&&(n.completed=!0,n.messages.length>0?t(n.messages.join("\n\n")):e(new Error("Execution timeout")),this.activeExecutions.delete(l))},this.config.responseTimeout)}),d=this.activeExecutions.get(l);let h=0;const u=setInterval(()=>{d.messages.length>h&&(h=d.messages.length)},100);try{for(;!d.completed;){if(d.messages.length>0){const t=d.messages.join("\n\n");yield yield be(t)}yield be(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield be(c);yield yield be(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield be(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var n,i,o;if(null===(n=this.config)||void 0===n?void 0:n.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(i=e.currentThread)||void 0===i?void 0:i.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 ve(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,n=URL.createObjectURL(t),i=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:n,previewUrl:s===X.Image?n:void 0,uploadProgress:100,metadata:{provider:"workflow-socket",uploadedAt:(new Date).toISOString(),base64:i}}})}fileToBase64(t){return new Promise((e,n)=>{const i=new FileReader;i.onload=()=>{const t=i.result,n=t.split(",")[1]||t;e(n)},i.onerror=n,i.readAsDataURL(t)})}determineFileType(t){return t.startsWith("image/")?X.Image:t.startsWith("video/")?X.Video:t.startsWith("audio/")?X.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?X.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?X.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?X.Code:X.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2873
|
+
*/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())})},xe=function(t){return this instanceof xe?(this.v=t,this):new xe(t)},we=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 xe?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 we(this,arguments,function*(){var i,n;if(!this.connected||!this.socket||!this.config)return yield yield xe(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield xe(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 xe(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield xe(a.text().catch(()=>a.statusText));return yield yield xe(this.formatError(`${a.status} ${a.statusText}`,t)),yield xe(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(i=yield xe(a.json().catch(()=>({}))))||void 0===i?void 0:i.executionId);if(!l)return yield yield xe(this.formatError("Execution Error","No execution ID received from server")),yield xe(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 xe(t)}yield xe(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield xe(d);yield yield xe(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield xe(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===X.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/")?X.Image:t.startsWith("video/")?X.Video:t.startsWith("audio/")?X.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?X.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?X.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?X.Code:X.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2716
2874
|
/**
|
|
2717
2875
|
* @license
|
|
2718
2876
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2719
2877
|
* SPDX-License-Identifier: MIT
|
|
2720
|
-
*/var we=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},_e=function(t){return this instanceof _e?(this.v=t,this):new _e(t)},$e=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=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,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof _e?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const ke={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",ping:"ping",pong:"pong",toolCall:"tool:call",toolCallEnd:"tool:end"};class Se{constructor(){this.id="native-websocket",this.name="Native WebSocket Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.ws=null,this.config=null,this.connected=!1,this.responseResolvers=new Map,this.reconnectAttempt=0,this.reconnectTimer=null,this.heartbeatTimer=null,this.pongTimer=null,this.intentionalClose=!1,this.messageListeners=new Map}connect(t){return we(this,void 0,void 0,function*(){var e,n,i,o,s,r,a,l,c,d;if(!t.url)throw new Error("WebSocket URL is required");return this.config=Object.assign(Object.assign({},t),{messageTypes:Object.assign(Object.assign({},ke),t.messageTypes),typeField:null!==(e=t.typeField)&&void 0!==e?e:"type",autoReconnect:null===(n=t.autoReconnect)||void 0===n||n,maxReconnectAttempts:null!==(i=t.maxReconnectAttempts)&&void 0!==i?i:5,reconnectBaseDelay:null!==(o=t.reconnectBaseDelay)&&void 0!==o?o:1e3,reconnectMaxDelay:null!==(s=t.reconnectMaxDelay)&&void 0!==s?s:3e4,connectionTimeout:null!==(r=t.connectionTimeout)&&void 0!==r?r:1e4,responseTimeout:null!==(a=t.responseTimeout)&&void 0!==a?a:3e4,enableHeartbeat:null===(l=t.enableHeartbeat)||void 0===l||l,heartbeatInterval:null!==(c=t.heartbeatInterval)&&void 0!==c?c:3e4,heartbeatTimeout:null!==(d=t.heartbeatTimeout)&&void 0!==d?d:1e4}),this.intentionalClose=!1,this.reconnectAttempt=0,this.createConnection()})}createConnection(){return new Promise((t,e)=>{const n=this.config;if(!n)return void e(new Error("Provider not configured"));const i=this.buildUrl();try{this.ws=n.protocols?new WebSocket(i,n.protocols):new WebSocket(i)}catch(t){return void e(new Error(`Failed to create WebSocket: ${t instanceof Error?t.message:String(t)}`))}const o=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),e(new Error("WebSocket connection timeout")))},n.connectionTimeout);this.ws.onopen=()=>{var e,n;clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,console.log("[NativeWebSocketProvider] Connected"),null===(n=null===(e=this.config)||void 0===e?void 0:e.onConnectionChange)||void 0===n||n.call(e,!0),this.startHeartbeat(),t()},this.ws.onclose=t=>{var n,i;clearTimeout(o);const s=this.connected;this.connected=!1,this.stopHeartbeat(),console.log("[NativeWebSocketProvider] Disconnected:",t.code,t.reason),s&&(null===(i=null===(n=this.config)||void 0===n?void 0:n.onConnectionChange)||void 0===i||i.call(n,!1));for(const[t,e]of this.responseResolvers)e.chunks.length>0?e.resolve(e.chunks.join("")):e.reject(new Error("WebSocket connection closed")),this.responseResolvers.delete(t);!this.intentionalClose&&s?this.attemptReconnect():s||e(new Error(`WebSocket connection failed (code: ${t.code})`))},this.ws.onerror=t=>{console.error("[NativeWebSocketProvider] Error:",t)},this.ws.onmessage=t=>{this.handleMessage(t)}})}buildUrl(){const t=this.config;if(!t)return"";let e=t.url;const n=t.queryParams;if(n&&Object.keys(n).length>0){const t=e.includes("?")?"&":"?";e=`${e}${t}${Object.entries(n).map(([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&")}`}return e}handleMessage(t){var e,n,i;if(!this.config)return;const o=this.parseMessageData(t.data);if(!o)return;const s=o[null!==(e=this.config.typeField)&&void 0!==e?e:"type"],r=this.config.messageTypes;if(s!==r.pong)if(s!==r.ping){if(s===r.toolCall){const t=o.name||o.toolName||o.function||"unknown";return null===(n=this.onToolCall)||void 0===n||n.call(this,t),void this.dispatchToListeners(s,o)}if(s===r.toolCallEnd)return null===(i=this.onToolCallEnd)||void 0===i||i.call(this),void this.dispatchToListeners(s,o);this.dispatchToListeners(s,o),s!==r.response?s!==r.stream?s===r.error&&this.handleErrorMessage(o):this.handleStreamMessage(o):this.handleResponseMessage(o)}else this.send(r.pong,{timestamp:Date.now()});else this.handlePong()}parseMessageData(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return console.warn("[NativeWebSocketProvider] Non-JSON message received:",t),null}}dispatchToListeners(t,e){if(!t)return;const n=this.messageListeners.get(t);if(n)for(const t of n)try{t(e)}catch(t){console.error("[NativeWebSocketProvider] Listener error:",t)}}handleResponseMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=this.extractMessageContent(t);n.resolve(i),this.responseResolvers.delete(e)}}handleStreamMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){n.isStreaming=!0;const e=this.extractMessageContent(t);n.chunks.push(e)}}handleErrorMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=t.error||t.message||"Unknown error";n.reject(new Error(i)),this.responseResolvers.delete(e)}}getLatestResolver(){const t=Array.from(this.responseResolvers.keys()).at(-1);return void 0!==t?this.responseResolvers.get(t):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessageContent(t){var e,n,i;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===(n=t.data)||void 0===n?void 0:n.message)?t.data.message:(null===(i=t.data)||void 0===i?void 0:i.output)?JSON.stringify(t.data.output):JSON.stringify(t)}startHeartbeat(){var t;if(!(null===(t=this.config)||void 0===t?void 0:t.enableHeartbeat))return;this.stopHeartbeat();const e=this.config.messageTypes;this.heartbeatTimer=setInterval(()=>{var t,n,i;this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN&&(this.send(e.ping,{timestamp:Date.now()}),this.pongTimer=setTimeout(()=>{var t;console.warn("[NativeWebSocketProvider] Heartbeat timeout — closing connection"),null===(t=this.ws)||void 0===t||t.close(4e3,"Heartbeat timeout")},null!==(i=null===(n=this.config)||void 0===n?void 0:n.heartbeatTimeout)&&void 0!==i?i:1e4))},this.config.heartbeatInterval)}handlePong(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}attemptReconnect(){var t,e,n,i,o,s;if(!(null===(t=this.config)||void 0===t?void 0:t.autoReconnect))return;const r=null!==(e=this.config.maxReconnectAttempts)&&void 0!==e?e:5;if(this.reconnectAttempt>=r)return void console.error("[NativeWebSocketProvider] Max reconnection attempts reached");this.reconnectAttempt++;const a=null!==(n=this.config.reconnectBaseDelay)&&void 0!==n?n:1e3,l=null!==(i=this.config.reconnectMaxDelay)&&void 0!==i?i:3e4,c=Math.min(a*Math.pow(2,this.reconnectAttempt-1)+Math.random()*a,l);console.log(`[NativeWebSocketProvider] Reconnecting in ${Math.round(c)}ms (attempt ${this.reconnectAttempt}/${r})`),null===(s=(o=this.config).onReconnectAttempt)||void 0===s||s.call(o,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>we(this,void 0,void 0,function*(){try{yield this.createConnection(),console.log("[NativeWebSocketProvider] Reconnected successfully")}catch(t){}}),c)}disconnect(){return we(this,void 0,void 0,function*(){this.intentionalClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.connected=!1,this.responseResolvers.clear(),this.messageListeners.clear(),console.log("[NativeWebSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN}sendMessage(t,e){return $e(this,arguments,function*(){if(!this.connected||!this.ws||!this.config)return yield yield _e(this.formatError("Not Connected","WebSocket is not connected. Please check your connection.")),yield _e(void 0);const n=`msg_${Date.now()}_${crypto.randomUUID().slice(0,9)}`,i=this.buildPayload(t,e,n);try{const t=new Promise((t,e)=>{var i,o;this.responseResolvers.set(n,{resolve:t,reject:e,chunks:[],isStreaming:!1}),setTimeout(()=>{const i=this.responseResolvers.get(n);i&&(i.chunks.length>0?t(i.chunks.join("")):e(new Error("Response timeout")),this.responseResolvers.delete(n))},null!==(o=null===(i=this.config)||void 0===i?void 0:i.responseTimeout)&&void 0!==o?o:3e4)}),e=this.config.messageTypes;if(this.send(e.send,Object.assign(Object.assign({},i),{messageId:n})),this.config.messageTypes.stream){const e=this.responseResolvers.get(n);let i=0;const o=setInterval(()=>{e&&e.chunks.length>i&&(i=e.chunks.length)},50);try{const e=yield _e(t);clearInterval(o),yield yield _e(e)}catch(t){throw clearInterval(o),t}}else{const e=yield _e(t);yield yield _e(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield _e(this.formatError("WebSocket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}send(t,e){var n;if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.config){const i=null!==(n=this.config.typeField)&&void 0!==n?n:"type",o=Object.assign({[i]:t},e);this.ws.send(JSON.stringify(o))}}onMessage(t,e){var n;return this.messageListeners.has(t)||this.messageListeners.set(t,new Set),null===(n=this.messageListeners.get(t))||void 0===n||n.add(e),()=>{const n=this.messageListeners.get(t);n&&(n.delete(e),0===n.size&&this.messageListeners.delete(t))}}getWebSocket(){return this.ws}buildPayload(t,e,n){var i,o,s;if(null===(i=this.config)||void 0===i?void 0:i.buildPayload){const i=this.config.buildPayload(t,e);return Object.assign(Object.assign({},i),{messageId:n})}return{messageId:n,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}))}}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[NativeWebSocketProvider] Error:",t)}}
|
|
2878
|
+
*/var $e=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())})},ke=function(t){return this instanceof ke?(this.v=t,this):new ke(t)},Se=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 ke?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 Pe={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",ping:"ping",pong:"pong",toolCall:"tool:call",toolCallEnd:"tool:end"};class Me{constructor(){this.id="native-websocket",this.name="Native WebSocket Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.ws=null,this.config=null,this.connected=!1,this.responseResolvers=new Map,this.reconnectAttempt=0,this.reconnectTimer=null,this.heartbeatTimer=null,this.pongTimer=null,this.intentionalClose=!1,this.messageListeners=new Map}connect(t){return $e(this,void 0,void 0,function*(){var e,i,n,o,s,r,a,l,d,c;if(!t.url)throw new Error("WebSocket URL is required");return this.config=Object.assign(Object.assign({},t),{messageTypes:Object.assign(Object.assign({},Pe),t.messageTypes),typeField:null!==(e=t.typeField)&&void 0!==e?e:"type",autoReconnect:null===(i=t.autoReconnect)||void 0===i||i,maxReconnectAttempts:null!==(n=t.maxReconnectAttempts)&&void 0!==n?n:5,reconnectBaseDelay:null!==(o=t.reconnectBaseDelay)&&void 0!==o?o:1e3,reconnectMaxDelay:null!==(s=t.reconnectMaxDelay)&&void 0!==s?s:3e4,connectionTimeout:null!==(r=t.connectionTimeout)&&void 0!==r?r:1e4,responseTimeout:null!==(a=t.responseTimeout)&&void 0!==a?a:3e4,enableHeartbeat:null===(l=t.enableHeartbeat)||void 0===l||l,heartbeatInterval:null!==(d=t.heartbeatInterval)&&void 0!==d?d:3e4,heartbeatTimeout:null!==(c=t.heartbeatTimeout)&&void 0!==c?c:1e4}),this.intentionalClose=!1,this.reconnectAttempt=0,this.createConnection()})}createConnection(){return new Promise((t,e)=>{const i=this.config;if(!i)return void e(new Error("Provider not configured"));const n=this.buildUrl();try{this.ws=i.protocols?new WebSocket(n,i.protocols):new WebSocket(n)}catch(t){return void e(new Error(`Failed to create WebSocket: ${t instanceof Error?t.message:String(t)}`))}const o=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),e(new Error("WebSocket connection timeout")))},i.connectionTimeout);this.ws.onopen=()=>{var e,i;clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,console.log("[NativeWebSocketProvider] Connected"),null===(i=null===(e=this.config)||void 0===e?void 0:e.onConnectionChange)||void 0===i||i.call(e,!0),this.startHeartbeat(),t()},this.ws.onclose=t=>{var i,n;clearTimeout(o);const s=this.connected;this.connected=!1,this.stopHeartbeat(),console.log("[NativeWebSocketProvider] Disconnected:",t.code,t.reason),s&&(null===(n=null===(i=this.config)||void 0===i?void 0:i.onConnectionChange)||void 0===n||n.call(i,!1));for(const[t,e]of this.responseResolvers)e.chunks.length>0?e.resolve(e.chunks.join("")):e.reject(new Error("WebSocket connection closed")),this.responseResolvers.delete(t);!this.intentionalClose&&s?this.attemptReconnect():s||e(new Error(`WebSocket connection failed (code: ${t.code})`))},this.ws.onerror=t=>{console.error("[NativeWebSocketProvider] Error:",t)},this.ws.onmessage=t=>{this.handleMessage(t)}})}buildUrl(){const t=this.config;if(!t)return"";let e=t.url;const i=t.queryParams;if(i&&Object.keys(i).length>0){const t=e.includes("?")?"&":"?";e=`${e}${t}${Object.entries(i).map(([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&")}`}return e}handleMessage(t){var e,i,n;if(!this.config)return;const o=this.parseMessageData(t.data);if(!o)return;const s=o[null!==(e=this.config.typeField)&&void 0!==e?e:"type"],r=this.config.messageTypes;if(s!==r.pong)if(s!==r.ping){if(s===r.toolCall){const t=o.name||o.toolName||o.function||"unknown";return null===(i=this.onToolCall)||void 0===i||i.call(this,t),void this.dispatchToListeners(s,o)}if(s===r.toolCallEnd)return null===(n=this.onToolCallEnd)||void 0===n||n.call(this),void this.dispatchToListeners(s,o);this.dispatchToListeners(s,o),s!==r.response?s!==r.stream?s===r.error&&this.handleErrorMessage(o):this.handleStreamMessage(o):this.handleResponseMessage(o)}else this.send(r.pong,{timestamp:Date.now()});else this.handlePong()}parseMessageData(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return console.warn("[NativeWebSocketProvider] Non-JSON message received:",t),null}}dispatchToListeners(t,e){if(!t)return;const i=this.messageListeners.get(t);if(i)for(const t of i)try{t(e)}catch(t){console.error("[NativeWebSocketProvider] Listener error:",t)}}handleResponseMessage(t){const e=this.extractMessageId(t),i=this.responseResolvers.get(e)||this.getLatestResolver();if(i){const n=this.extractMessageContent(t);i.resolve(n),this.responseResolvers.delete(e)}}handleStreamMessage(t){const e=this.extractMessageId(t),i=this.responseResolvers.get(e)||this.getLatestResolver();if(i){i.isStreaming=!0;const e=this.extractMessageContent(t);i.chunks.push(e)}}handleErrorMessage(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)}}getLatestResolver(){const t=Array.from(this.responseResolvers.keys()).at(-1);return void 0!==t?this.responseResolvers.get(t):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessageContent(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)}startHeartbeat(){var t;if(!(null===(t=this.config)||void 0===t?void 0:t.enableHeartbeat))return;this.stopHeartbeat();const e=this.config.messageTypes;this.heartbeatTimer=setInterval(()=>{var t,i,n;this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN&&(this.send(e.ping,{timestamp:Date.now()}),this.pongTimer=setTimeout(()=>{var t;console.warn("[NativeWebSocketProvider] Heartbeat timeout — closing connection"),null===(t=this.ws)||void 0===t||t.close(4e3,"Heartbeat timeout")},null!==(n=null===(i=this.config)||void 0===i?void 0:i.heartbeatTimeout)&&void 0!==n?n:1e4))},this.config.heartbeatInterval)}handlePong(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}attemptReconnect(){var t,e,i,n,o,s;if(!(null===(t=this.config)||void 0===t?void 0:t.autoReconnect))return;const r=null!==(e=this.config.maxReconnectAttempts)&&void 0!==e?e:5;if(this.reconnectAttempt>=r)return void console.error("[NativeWebSocketProvider] Max reconnection attempts reached");this.reconnectAttempt++;const a=null!==(i=this.config.reconnectBaseDelay)&&void 0!==i?i:1e3,l=null!==(n=this.config.reconnectMaxDelay)&&void 0!==n?n:3e4,d=Math.min(a*Math.pow(2,this.reconnectAttempt-1)+Math.random()*a,l);console.log(`[NativeWebSocketProvider] Reconnecting in ${Math.round(d)}ms (attempt ${this.reconnectAttempt}/${r})`),null===(s=(o=this.config).onReconnectAttempt)||void 0===s||s.call(o,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>$e(this,void 0,void 0,function*(){try{yield this.createConnection(),console.log("[NativeWebSocketProvider] Reconnected successfully")}catch(t){}}),d)}disconnect(){return $e(this,void 0,void 0,function*(){this.intentionalClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.connected=!1,this.responseResolvers.clear(),this.messageListeners.clear(),console.log("[NativeWebSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN}sendMessage(t,e){return Se(this,arguments,function*(){if(!this.connected||!this.ws||!this.config)return yield yield ke(this.formatError("Not Connected","WebSocket is not connected. Please check your connection.")),yield ke(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)=>{var n,o;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))},null!==(o=null===(n=this.config)||void 0===n?void 0:n.responseTimeout)&&void 0!==o?o:3e4)}),e=this.config.messageTypes;if(this.send(e.send,Object.assign(Object.assign({},n),{messageId:i})),this.config.messageTypes.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 ke(t);clearInterval(o),yield yield ke(e)}catch(t){throw clearInterval(o),t}}else{const e=yield ke(t);yield yield ke(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ke(this.formatError("WebSocket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}send(t,e){var i;if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.config){const n=null!==(i=this.config.typeField)&&void 0!==i?i:"type",o=Object.assign({[n]:t},e);this.ws.send(JSON.stringify(o))}}onMessage(t,e){var i;return this.messageListeners.has(t)||this.messageListeners.set(t,new Set),null===(i=this.messageListeners.get(t))||void 0===i||i.add(e),()=>{const i=this.messageListeners.get(t);i&&(i.delete(e),0===i.size&&this.messageListeners.delete(t))}}getWebSocket(){return this.ws}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}))}}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[NativeWebSocketProvider] Error:",t)}}
|
|
2721
2879
|
/**
|
|
2722
2880
|
* @license
|
|
2723
2881
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2724
2882
|
* SPDX-License-Identifier: MIT
|
|
2725
|
-
*/var
|
|
2883
|
+
*/var Te=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 Ee{constructor(t,e={}){this.id="persistence",this.name="Persistence Plugin",this.version="1.0.0",this.storage=t,this.storageKey=e.storageKey||"chatbot-state",e.autoSaveInterval&&(this.autoSaveInterval=setInterval(()=>{this.saveState()},e.autoSaveInterval))}onInit(t){this.controller=t,this.loadState(),console.log("[PersistencePlugin] Initialized")}onDestroy(){this.autoSaveInterval&&clearInterval(this.autoSaveInterval),this.saveState(),console.log("[PersistencePlugin] Destroyed")}onStateChange(){this.saveState()}saveState(){return Te(this,void 0,void 0,function*(){if(this.controller)try{const t=this.controller.getState();yield this.storage.save(this.storageKey,t),console.log("[PersistencePlugin] State saved")}catch(t){console.error("[PersistencePlugin] Error saving state:",t)}})}loadState(){return Te(this,void 0,void 0,function*(){if(this.controller)try{const t=yield this.storage.load(this.storageKey);t&&(this.controller.setState(t),console.log("[PersistencePlugin] State loaded"))}catch(t){console.error("[PersistencePlugin] Error loading state:",t)}})}clearStorage(){return Te(this,void 0,void 0,function*(){try{yield this.storage.remove(this.storageKey),console.log("[PersistencePlugin] Storage cleared")}catch(t){console.error("[PersistencePlugin] Error clearing storage:",t)}})}}
|
|
2726
2884
|
/**
|
|
2727
2885
|
* @license
|
|
2728
2886
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2729
2887
|
* SPDX-License-Identifier: MIT
|
|
2730
|
-
*/class
|
|
2888
|
+
*/class Ce{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()})}}
|
|
2731
2889
|
/**
|
|
2732
2890
|
* @license
|
|
2733
2891
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2734
2892
|
* SPDX-License-Identifier: MIT
|
|
2735
|
-
*/class
|
|
2893
|
+
*/class ze{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){}}}
|
|
2736
2894
|
/**
|
|
2737
2895
|
* @license
|
|
2738
2896
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2739
2897
|
* SPDX-License-Identifier: MIT
|
|
2740
|
-
*/var
|
|
2898
|
+
*/var Oe=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 Ie extends ze{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 Oe(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 "}}
|
|
2741
2899
|
/**
|
|
2742
2900
|
* @license
|
|
2743
2901
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2744
2902
|
* SPDX-License-Identifier: MIT
|
|
2745
|
-
*/var Oe=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Ie extends Ee{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 Oe(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 n,i=t;for(;null!==(n=e.exec(t));)try{const t=JSON.parse(n[1]),e=this.renderFlightCard(t);i=i.replace(n[0],e)}catch(t){console.warn("[FlightCardPlugin] Failed to parse flight data:",t)}return i})}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:n,departureTime:i,arrivalTime:o,departureDate:s,arrivalDate:r,terminal:a,gate:l,arrivalTerminal:c,arrivalGate:d,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(n)}</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(i)}</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(n)}</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 ${c?`\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(c)}</span>\n </div>\n `:""}\n ${d?`\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(d)}</span>\n </div>\n `:void 0===d?`\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 /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .${this.cssPrefix} {\n background: #2a2a2a;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n }\n\n .${this.cssPrefix}__airport-code,\n .${this.cssPrefix}__city,\n .${this.cssPrefix}__info-value {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__flight-line::before {\n background: linear-gradient(to right, #444 0%, #444 100%);\n }\n\n .${this.cssPrefix}__plane-icon {\n background: #2a2a2a;\n color: #999;\n }\n\n .${this.cssPrefix}__duration {\n background: #2a2a2a;\n }\n\n .${this.cssPrefix}__divider {\n background: #444;\n }\n\n .${this.cssPrefix}__footer {\n border-top-color: #444;\n }\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 `}}
|
|
2903
|
+
*/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 `}}
|
|
2746
2904
|
/**
|
|
2747
2905
|
* @license
|
|
2748
2906
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2749
2907
|
* SPDX-License-Identifier: MIT
|
|
2750
|
-
*/class Re extends Ee{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),n=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: ${n}%"></div>\n </div>\n <div class="${this.cssPrefix}__progress-text">\n ${t.pagesPrinted} / ${t.totalPages} pages (${n}%)\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 /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .${this.cssPrefix} {\n background: #2a2a2a;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n border-left-color: #42a5f5;\n }\n\n .${this.cssPrefix}__title,\n .${this.cssPrefix}__detail-value {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__subtitle,\n .${this.cssPrefix}__detail-label {\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__job-id {\n background: #3a3a3a;\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__details {\n background: #333;\n }\n\n .${this.cssPrefix}__progress-bar {\n background: #444;\n }\n\n .${this.cssPrefix}__footer {\n border-top-color: #444;\n }\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 `}}
|
|
2908
|
+
*/class je 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 `}}
|
|
2751
2909
|
/**
|
|
2752
2910
|
* @license
|
|
2753
2911
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2754
2912
|
* SPDX-License-Identifier: MIT
|
|
2755
|
-
*/var
|
|
2913
|
+
*/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 ze{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)}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 "}}
|
|
2756
2914
|
/**
|
|
2757
2915
|
* @license
|
|
2758
2916
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2759
2917
|
* SPDX-License-Identifier: MIT
|
|
2760
|
-
*/class
|
|
2918
|
+
*/class Ne extends ze{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)}}
|
|
2761
2919
|
/**
|
|
2762
2920
|
* @license
|
|
2763
2921
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2764
2922
|
* SPDX-License-Identifier: MIT
|
|
2765
|
-
*/const Fe="nuraly:flow-diagram:split-width",Ne="nuraly:flow-diagram:panel-width",Be="nr-flow-diagram-editor";class Le extends HTMLElement{connectedCallback(){var t;const e=this.loadPanelWidth(),n=this.closestPanel();n&&(n.style.setProperty("width",`${e}px`),this._panelObserver=new ResizeObserver(()=>{const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ne,String(t))}),this._panelObserver.observe(n));const i=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){}i.innerHTML=`\n <style>${Le.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=i.querySelector(".editor-textarea");l&&(l.value=r);const c=localStorage.getItem(Fe);c&&requestAnimationFrame(()=>{const t=i.querySelector(".editor-pane");t&&(t.style.flex="none",t.style.width=`${c}px`)});const d=i.querySelector(".diagram-pane"),h=i.querySelector(".error-bar");l&&d&&h&&(l.addEventListener("input",()=>{try{const t=JSON.parse(l.value);if(t.Steps&&t.Transitions){d.innerHTML=this.renderDiagram(t);const e=i.querySelector(".header");if(e){const n=document.createElement("template");n.innerHTML=this.renderHeader(t).trim();const i=n.content.firstElementChild;i&&e.replaceWith(i)}}h.style.display="none"}catch(t){h.textContent=`Parse error: ${t.message}`,h.style.display="flex"}}),this.initResize(i))}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(Ne);return t?Math.max(300,Number.parseInt(t,10)):500}closestPanel(){var t,e,n,i;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!==(i=null!==(n=o.parentElement)&&void 0!==n?n:o.getRootNode().host)&&void 0!==i?i:null}return null}initResize(t){const e=t.querySelector(".split"),n=t.querySelector(".editor-pane"),i=t.querySelector(".resize-handle");if(!e||!n||!i)return;let o=!1,s=0,r=0;const a=t=>{if(!o)return;const i=t.clientX-s,a=e.getBoundingClientRect().width,l=Math.max(200,Math.min(r+i,a-200));n.style.flex="none",n.style.width=`${l}px`},l=()=>{if(!o)return;o=!1,i.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="";const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Fe,String(t)),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};i.addEventListener("mousedown",t=>{const e=t;e.preventDefault(),o=!0,s=e.clientX,r=n.getBoundingClientRect().width,i.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,n;const i=null!==(e=null==t?void 0:t.Name)&&void 0!==e?e:"Workflow",o=(null!==(n=null==t?void 0:t.DocflowTags)&&void 0!==n?n:[]).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(i)}</span>\n ${o}\n </div>\n `}renderDiagram(t){var e,n;const i=this.buildOrderedSteps(t),o=[];for(let t=0;t<i.length;t++){const s=i[t];o.push("event"===s.type?this.renderEventNode(s.name,null!==(e=s.eventType)&&void 0!==e?e:""):this.renderStepNode(s.name,null!==(n=s.step)&&void 0!==n?n:{})),t<i.length-1&&o.push(this.renderConnector())}return`<div class="diagram">${o.join("")}</div>`}buildOrderedSteps(t){var e,n,i,o;const s=[],r=null===(e=t.Events)||void 0===e?void 0:e.StartEvent,a=null===(n=t.Events)||void 0===n?void 0:n.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 c=null!==(o=null===(i=l.StartEvent)||void 0===i?void 0:i.Target)&&void 0!==o?o:Object.keys(t.Steps)[0];const d=new Set;for(;c&&t.Steps[c]&&!d.has(c);){d.add(c),s.push({type:"step",name:c,step:t.Steps[c]});const e=l[c];if(!e||"EndEvent"===e.Target)break;c=e.Target}return a&&s.push({type:"event",name:a.Name||"End",eventType:"end"}),s}renderEventNode(t,e){const n="start"===e;return`\n <div class="node event-node ${n?"event-start":"event-end"}">\n <span class="event-icon">${n?"●":"■"}</span>\n <span class="event-label">${at(t)}</span>\n </div>\n `}renderStepNode(t,e){var n,i,o;const s=null!==(n=e.StepType)&&void 0!==n?n:"",r=null!==(o=null===(i=e.Description)||void 0===i?void 0:i.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 Ue extends Ee{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(Be)||customElements.define(Be,Le)}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>`:""}}
|
|
2923
|
+
*/const Le="nuraly:flow-diagram:split-width",Be="nuraly:flow-diagram:panel-width",Ue="nr-flow-diagram-editor";class We 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(Be,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>${We.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(Le);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(Be);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(Le,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 He extends ze{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(Ue)||customElements.define(Ue,We)}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>`:""}}
|
|
2766
2924
|
/**
|
|
2767
2925
|
* @license
|
|
2768
2926
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2769
2927
|
* SPDX-License-Identifier: MIT
|
|
2770
|
-
*/var
|
|
2928
|
+
*/var Je=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 qe extends ze{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 Je(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 `}}
|
|
2771
2929
|
/**
|
|
2772
2930
|
* @license
|
|
2773
2931
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2774
2932
|
* SPDX-License-Identifier: MIT
|
|
2775
|
-
*/var
|
|
2933
|
+
*/var Ve=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 Ge{constructor(){this.store=new Map}save(t,e){return Ve(this,void 0,void 0,function*(){this.store.set(t,JSON.parse(JSON.stringify(e)))})}load(t){return Ve(this,void 0,void 0,function*(){const e=this.store.get(t);return e?JSON.parse(JSON.stringify(e)):null})}remove(t){return Ve(this,void 0,void 0,function*(){this.store.delete(t)})}clear(){return Ve(this,void 0,void 0,function*(){this.store.clear()})}has(t){return Ve(this,void 0,void 0,function*(){return this.store.has(t)})}}class Ke{save(t,e){return Ve(this,void 0,void 0,function*(){try{localStorage.setItem(t,JSON.stringify(e))}catch(t){throw console.error("[LocalStorage] Save error:",t),new Error(`Failed to save to localStorage: ${t}`)}})}load(t){return Ve(this,void 0,void 0,function*(){try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(t){return console.error("[LocalStorage] Load error:",t),null}})}remove(t){return Ve(this,void 0,void 0,function*(){localStorage.removeItem(t)})}clear(){return Ve(this,void 0,void 0,function*(){Object.keys(localStorage).filter(t=>t.startsWith("chatbot-")).forEach(t=>{localStorage.removeItem(t)})})}has(t){return Ve(this,void 0,void 0,function*(){return null!==localStorage.getItem(t)})}}class Ye{constructor(t="chatbot-db",e="chatbot-store"){this.dbName=t,this.storeName=e}getDB(){return Ve(this,void 0,void 0,function*(){return this.db?this.db:new Promise((t,e)=>{const i=indexedDB.open(this.dbName,1);i.onerror=()=>e(i.error),i.onsuccess=()=>{this.db=i.result,t(this.db)},i.onupgradeneeded=t=>{const e=t.target.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}})})}save(t,e){return Ve(this,void 0,void 0,function*(){const i=yield this.getDB();return new Promise((n,o)=>{const s=i.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(e,t);s.onerror=()=>o(s.error),s.onsuccess=()=>n()})})}load(t){return Ve(this,void 0,void 0,function*(){const e=yield this.getDB();return new Promise((i,n)=>{const o=e.transaction([this.storeName],"readonly").objectStore(this.storeName).get(t);o.onerror=()=>n(o.error),o.onsuccess=()=>i(o.result||null)})})}remove(t){return Ve(this,void 0,void 0,function*(){const e=yield this.getDB();return new Promise((i,n)=>{const o=e.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(t);o.onerror=()=>n(o.error),o.onsuccess=()=>i()})})}clear(){return Ve(this,void 0,void 0,function*(){const t=yield this.getDB();return new Promise((e,i)=>{const n=t.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();n.onerror=()=>i(n.error),n.onsuccess=()=>e()})})}has(t){return Ve(this,void 0,void 0,function*(){return null!==(yield this.load(t))})}}
|
|
2776
2934
|
/**
|
|
2777
2935
|
* @license
|
|
2778
2936
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2779
2937
|
* SPDX-License-Identifier: MIT
|
|
2780
|
-
*/class
|
|
2938
|
+
*/class Xe{constructor(t){this.host=t,t.addController(this)}hostConnected(){}hostDisconnected(){}handleMessagesUpdate(){var t;if(!this.host.autoScroll)return;(null===(t=this.host.shadowRoot)||void 0===t?void 0:t.querySelector(".messages"))&&this.scrollToBottom()}scrollToBottom(){var t;const e=null===(t=this.host.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight})}}
|
|
2781
2939
|
/**
|
|
2782
2940
|
* @license
|
|
2783
2941
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
@@ -2790,4 +2948,4 @@ var Gt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){
|
|
|
2790
2948
|
* Pipeline:
|
|
2791
2949
|
* input blob → AudioContext.decodeAudioData → BufferSource → MediaStreamDestination
|
|
2792
2950
|
* → MediaRecorder(ogg/opus, 32 kbps) → output blob
|
|
2793
|
-
*/var
|
|
2951
|
+
*/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())})};const Ze="audio/ogg;codecs=opus";function ti(){try{return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported(Ze)}catch(t){return!1}}var ei=Object.freeze({__proto__:null,canEncodeOgg:ti,compressToOpus:function(t,e){return Qe(this,void 0,void 0,function*(){if(!ti()){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:Ze,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:Ze}),mimeType:Ze,ext:"ogg"}})}});export{Ce as AnalyticsPlugin,De as ArtifactPlugin,ze as ChatPluginBase,Q as ChatbotActionType,Xt as ChatbotCoreController,X as ChatbotFileType,V as ChatbotLoadingType,Y as ChatbotMessageState,Xe as ChatbotScrollController,q as ChatbotSender,G as ChatbotSize,K as ChatbotVariant,se 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,Ct as EventBus,st as FILE_TYPE_MAPPINGS,Ft as FileHandler,Ae as FlightCardPlugin,He as FlowDiagramPlugin,Ye as IndexedDBStorage,Ne as JsonGraphRendererPlugin,Ke as LocalStorageAdapter,Ie as MarkdownPlugin,Ge as MemoryStorage,It as MessageHandler,ue as MockProvider,pe as MockProviders,Dt as ModuleHandler,Me as NativeWebSocketProvider,Et as NrChatbotElement,ee as OpenAIProvider,Ee as PersistencePlugin,Vt as PluginService,je as PrintJobCardPlugin,Bt as ProviderService,qe as SelectionCardPlugin,be as SocketProvider,Ot as StateHandler,Jt as StorageService,Nt as SuggestionHandler,At as ThreadHandler,zt as ValidationError,Wt as ValidationService,_e as WorkflowSocketProvider};
|