@nuraly/lumenui 0.3.6 β†’ 0.3.8

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.
@@ -20,12 +20,12 @@ class v{constructor(t){this.t=t=>{"ready"===t.detail.status&&this.host.requestUp
20
20
  * Copyright 2020 Google LLC
21
21
  * SPDX-License-Identifier: BSD-3-Clause
22
22
  */
23
- class x{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}}
23
+ class y{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._resolve=t,this._reject=e})}resolve(t){this.settled=!0,this._resolve(t)}reject(t){this.settled=!0,this._reject(t)}}
24
24
  /**
25
25
  * @license
26
26
  * Copyright 2014 Travis Webb
27
27
  * SPDX-License-Identifier: MIT
28
- */const y=[];for(let t=0;t<256;t++)y[t]=(t>>4&15).toString(16)+(15&t).toString(16);function w(t,e){return(e?"h":"s")+function(t){let e=0,i=8997,n=0,o=33826,s=0,r=40164,a=0,l=52210;for(let d=0;d<t.length;d++)i^=t.charCodeAt(d),e=435*i,n=435*o,s=435*r,a=435*l,s+=i<<8,a+=o<<8,n+=e>>>16,i=65535&e,s+=n>>>16,o=65535&n,l=a+(s>>>16)&65535,r=65535&s;return y[l>>8]+y[255&l]+y[r>>8]+y[255&r]+y[o>>8]+y[255&o]+y[i>>8]+y[255&i]}
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
@@ -40,7 +40,7 @@ class x{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
40
40
  * @license
41
41
  * Copyright 2021 Google LLC
42
42
  * SPDX-License-Identifier: BSD-3-Clause
43
- */(e),o=t[n];if(o){if("string"==typeof o)return o;if("strTag"in o)return p(o.strings,e.values,o.values);{let t=_.get(o);return void 0===t&&(t=o.values,_.set(o,t)),{...o,values:t.map(t=>e.values[t])}}}}return f(e)}function S(t){window.dispatchEvent(new CustomEvent(u,{detail:t}))}let P,M,T,E,C,z="",O=new x;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 x),S({status:"loading",loadingLocale:t});return(t===M?Promise.resolve({templates:void 0}):E(t)).then(i=>{I===e&&(z=t,P=void 0,C=i.templates,S({status:"ready",readyLocale:t}),O.resolve())},i=>{I===e&&(S({status:"error",errorLocale:t,errorMessage:i.toString()}),O.reject(i))}),O.promise};var D=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%;
@@ -1679,7 +1679,6 @@ class x{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
1679
1679
  justify-content: center;
1680
1680
  background: #e0e0e0;
1681
1681
  transition: background 0.15s;
1682
- z-index: 1;
1683
1682
  }
1684
1683
  .artifact-panel__resize-handle:hover,
1685
1684
  .artifact-panel__resize-handle--active {
@@ -1962,7 +1961,7 @@ class x{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
1962
1961
  * @license
1963
1962
  * Copyright 2023 Nuraly, Laabidi Aymen
1964
1963
  * SPDX-License-Identifier: MIT
1965
- */;const F=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;
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;
1966
1965
  /**
1967
1966
  * @license
1968
1967
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2385,7 +2384,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
2385
2384
  * @license
2386
2385
  * Copyright 2023 Nuraly, Laabidi Aymen
2387
2386
  * SPDX-License-Identifier: MIT
2388
- */function xt(t,e,n){const o=t.messages.length>0?t.messages[t.messages.length-1]:null,s=o&&"string"==typeof o.text?o.text:"";return i`
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`
2389
2388
  <div
2390
2389
  class="thread-item ${a({"thread-item--active":t.id===e.activeThreadId})}"
2391
2390
  @click=${()=>n.onSelectThread(t.id)}
@@ -2443,7 +2442,7 @@ function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
2443
2442
  </div>
2444
2443
  <div class="thread-item__timestamp">${rt(t.updatedAt)}</div>
2445
2444
  </div>
2446
- `}function yt(t,n){if(!t.isOpen||!t.file)return e;const o=t.file,s=o.mimeType.startsWith("image/"),r="application/pdf"===o.mimeType||o.name.toLowerCase().endsWith(".pdf");return i`
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`
2447
2446
  <nr-modal
2448
2447
  .open=${t.isOpen}
2449
2448
  size="large"
@@ -2576,14 +2575,14 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
2576
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>
2577
2576
  ${m("Bookmarks")}
2578
2577
  </div>
2579
- ${d(o,t=>t.id,e=>xt(e,t,n))}
2578
+ ${d(o,t=>t.id,e=>yt(e,t,n))}
2580
2579
  </div>
2581
2580
  `:e}
2582
2581
  ${s.length>0||0===o.length?i`
2583
2582
  ${o.length>0?i`
2584
2583
  <div class="thread-section__label">${m("All Conversations")}</div>
2585
2584
  `:e}
2586
- ${d(s,t=>t.id,e=>xt(e,t,n))}
2585
+ ${d(s,t=>t.id,e=>yt(e,t,n))}
2587
2586
  ${0===s.length&&0===o.length?i`
2588
2587
  <p class="empty-msg">${m("No conversations yet")}</p>
2589
2588
  `:e}
@@ -2756,7 +2755,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
2756
2755
  * @license
2757
2756
  * Copyright 2023 Nuraly, Laabidi Aymen
2758
2757
  * SPDX-License-Identifier: MIT
2759
- */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(F(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`
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`
2760
2759
  <div
2761
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})}"
2762
2761
  dir=${this.isRTL?"rtl":"ltr"}
@@ -2769,7 +2768,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
2769
2768
  ${$t(e,n)}
2770
2769
  </div>
2771
2770
 
2772
- ${yt({isOpen:this.isFilePreviewModalOpen,file:this.previewFile},{onClose:this.handleFilePreviewModalClose.bind(this)})}
2771
+ ${xt({isOpen:this.isFilePreviewModalOpen,file:this.previewFile},{onClose:this.handleFilePreviewModalClose.bind(this)})}
2773
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`
2774
2773
  <span class="module-display-single">
2775
2774
  ${(null==t?void 0:t.icon)?i`<nr-icon name="${t.icon}" size="small"></nr-icon>`:e}
@@ -2779,7 +2778,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
2779
2778
  <span class="module-display-multiple">
2780
2779
  ${t} ${m("modules selected")}
2781
2780
  </span>
2782
- `}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=D,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);
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);
2783
2782
  /**
2784
2783
  * @license
2785
2784
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2810,12 +2809,12 @@ class Ct{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(
2810
2809
  * @license
2811
2810
  * Copyright 2023 Nuraly, Laabidi Aymen
2812
2811
  * SPDX-License-Identifier: MIT
2813
- */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 Dt{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)}`}}
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)}`}}
2814
2813
  /**
2815
2814
  * @license
2816
2815
  * Copyright 2023 Nuraly, Laabidi Aymen
2817
2816
  * SPDX-License-Identifier: MIT
2818
- */class Ft{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:[]})}}
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:[]})}}
2819
2818
  /**
2820
2819
  * @license
2821
2820
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2825,7 +2824,7 @@ class Ct{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(
2825
2824
  * @license
2826
2825
  * Copyright 2023 Nuraly, Laabidi Aymen
2827
2826
  * SPDX-License-Identifier: MIT
2828
- */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)}}
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){const e=/<div data-placeholder-id="[^"]*">[\s\S]*?<\/div>/;t.hasPlaceholder&&i&&e.test(i.text)?(i.text=i.text.replace(e,a),this.messageHandler.updateMessage(i.id,{text:i.text})):t.hasPlaceholder&&e.test(u)?(u=u.replace(e,a),p=!0):(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)}}
2829
2828
  /**
2830
2829
  * @license
2831
2830
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2846,7 +2845,7 @@ class Ct{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(
2846
2845
  * Copyright 2023 Nuraly, Laabidi Aymen
2847
2846
  * SPDX-License-Identifier: MIT
2848
2847
  */
2849
- 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 Dt(this.stateHandler,this.eventBus),this.moduleHandler=new Ft(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)}}
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)}}
2850
2849
  /**
2851
2850
  * @license
2852
2851
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2871,7 +2870,7 @@ var Yt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
2871
2870
  * @license
2872
2871
  * Copyright 2024 Nuraly, Laabidi Aymen
2873
2872
  * SPDX-License-Identifier: MIT
2874
- */var xe=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){try{l(n.next(t))}catch(t){s(t)}}function a(t){try{l(n.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof i?e:new i(function(t){t(e)})).then(r,a)}l((n=n.apply(t,e||[])).next())})},ye=function(t){return this instanceof ye?(this.v=t,this):new ye(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 ye?Promise.resolve(i.value.v).then(l,d):c(s[0][2],i)}catch(t){c(s[0][3],t)}var i}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class _e{constructor(){this.id="workflow-socket",this.name="Workflow Socket Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.sessionId=`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`,this.activeExecutions=new Map}connect(t){return xe(this,void 0,void 0,function*(){if(!t.workflowId)throw new Error("Workflow ID is required");this.config=Object.assign({socketUrl:t.socketUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:8000"),socketPath:t.socketPath||"/__nk_socketio/",triggerEndpoint:t.triggerEndpoint||"/api/v1/workflows/{workflowId}/trigger/chat",responseTimeout:t.responseTimeout||6e4},t);const e=`${this.config.socketUrl}/nk/apps/workflows/:workflowId`;return this.socket=h(e,{path:this.config.socketPath,query:{l:JSON.stringify({workflowId:this.config.workflowId})},autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const i=setTimeout(()=>{e(new Error("Socket connection timeout"))},3e4);this.socket.on("connect",()=>{clearTimeout(i),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(i),console.error("[WorkflowSocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[WorkflowSocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}subscribeToWorkflow(t){this.socket&&(this.socket.emit("nk:subscribe:workflow",{workflowId:t}),console.log("[WorkflowSocketProvider] Subscribed to workflow:",t))}subscribeToExecution(t){this.socket&&(this.socket.emit("nk:subscribe:execution",{executionId:t}),console.log("[WorkflowSocketProvider] Subscribed to execution:",t))}setupEventListeners(){this.socket&&(this.socket.onAny((t,...e)=>{console.log("[WorkflowSocketProvider] RAW event:",t,e[0])}),this.socket.on("nk:data",t=>{(null==t?void 0:t.event)&&t.data&&this._handleEvent(t.event,t.data)}),this.socket.on("execution:chat-message",t=>this._handleEvent("execution:chat-message",t)),this.socket.on("execution:started",t=>this._handleEvent("execution:started",t)),this.socket.on("execution:completed",t=>this._handleEvent("execution:completed",t)),this.socket.on("execution:failed",t=>this._handleEvent("execution:failed",t)),this.socket.on("execution:node-started",t=>this._handleEvent("execution:node-started",t)),this.socket.on("execution:node-completed",t=>this._handleEvent("execution:node-completed",t)))}_handleEvent(t,e){var i,n,o,s,r;switch(t){case"execution:chat-message":{const t=e.executionId,o=e.message;if(console.log("[WorkflowSocketProvider] Chat message received:",t,o),!t||!o)return;const s=this.activeExecutions.get(t);if(!s)return void(null===(n=null===(i=this.config)||void 0===i?void 0:i.onMessage)||void 0===n||n.call(i,o));s.completed||s.messages.push(o);break}case"execution:started":console.log("[WorkflowSocketProvider] Execution started (event):",e.executionId);break;case"execution:completed":{const t=e.executionId;if(console.log("[WorkflowSocketProvider] Execution completed:",t),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0;let n="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)n=this.config.extractResponse(e);else if(i.messages.length>0)n=i.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;n=t.response||t.message||t.result||JSON.stringify(t)}catch(t){n=e.outputData}i.resolve(n||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,i=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,i),!t)return;const n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0,n.reject(new Error(i)),this.activeExecutions.delete(t);break}case"execution:node-started":console.log("[WorkflowSocketProvider] Node started:",e.nodeName),e.nodeName&&(null===(s=this.onNodeStarted)||void 0===s||s.call(this,e.nodeName));break;case"execution:node-completed":console.log("[WorkflowSocketProvider] Node completed:",e.nodeName),e.nodeName&&(null===(r=this.onNodeCompleted)||void 0===r||r.call(this,e.nodeName))}}disconnect(){return xe(this,void 0,void 0,function*(){var t;this.socket&&((null===(t=this.config)||void 0===t?void 0:t.workflowId)&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.socket.disconnect(),this.socket=null),this.connected=!1,this.activeExecutions.clear(),console.log("[WorkflowSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return we(this,arguments,function*(){var i,n;if(!this.connected||!this.socket||!this.config)return yield yield ye(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield ye(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 ye(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield ye(a.text().catch(()=>a.statusText));return yield yield ye(this.formatError(`${a.status} ${a.statusText}`,t)),yield ye(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(i=yield ye(a.json().catch(()=>({}))))||void 0===i?void 0:i.executionId);if(!l)return yield yield ye(this.formatError("Execution Error","No execution ID received from server")),yield ye(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 ye(t)}yield ye(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield ye(d);yield yield ye(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ye(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var i,n,o;if(null===(i=this.config)||void 0===i?void 0:i.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(n=e.currentThread)||void 0===n?void 0:n.id)||this.sessionId,r={message:t,threadId:s,modules:e.selectedModules,metadata:e.metadata,files:(null===(o=e.uploadedFiles)||void 0===o?void 0:o.map(t=>{var e;return{id:t.id,name:t.name,type:t.type,mimeType:t.mimeType,url:t.url,base64:null===(e=t.metadata)||void 0===e?void 0:e.base64}}))||[]};return console.log("[WorkflowSocketProvider] buildInput threadId:",s,"files count:",r.files.length),r}setWorkflowId(t){this.config&&(this.socket&&this.config.workflowId&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.config.workflowId=t,this.socket&&this.connected&&this.subscribeToWorkflow(t))}getSocket(){return this.socket}uploadFile(t){return xe(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,i=URL.createObjectURL(t),n=yield this.fileToBase64(t),o=t.type||"application/octet-stream",s=this.determineFileType(o);return console.log(`[WorkflowSocketProvider] File prepared: ${t.name} (${t.size} bytes)`),{id:e,name:t.name,size:t.size,type:s,mimeType:o,url:i,previewUrl:s===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)}}
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)}}
2875
2874
  /**
2876
2875
  * @license
2877
2876
  * Copyright 2024 Nuraly, Laabidi Aymen
@@ -2896,22 +2895,22 @@ var Yt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
2896
2895
  * @license
2897
2896
  * Copyright 2023 Nuraly, Laabidi Aymen
2898
2897
  * SPDX-License-Identifier: MIT
2899
- */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 @media (prefers-color-scheme: dark) {\n .md-code { background: #0f1115; color: #eaeef2; }\n .md-inline-code { background: rgba(255,255,255,.08); }\n }\n "}}
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 "}}
2900
2899
  /**
2901
2900
  * @license
2902
2901
  * Copyright 2023 Nuraly, Laabidi Aymen
2903
2902
  * SPDX-License-Identifier: MIT
2904
- */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 /* 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 `}}
2905
2904
  /**
2906
2905
  * @license
2907
2906
  * Copyright 2023 Nuraly, Laabidi Aymen
2908
2907
  * SPDX-License-Identifier: MIT
2909
- */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 /* 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 `}}
2910
2909
  /**
2911
2910
  * @license
2912
2911
  * Copyright 2023 Nuraly, Laabidi Aymen
2913
2912
  * SPDX-License-Identifier: MIT
2914
- */var De=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 Fe 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 De(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 @media (prefers-color-scheme: dark) {\n .nr-artifact-card {\n background: #161b22;\n border-color: #30363d;\n }\n .nr-artifact-card:hover {\n background: #1c2128;\n border-color: #484f58;\n }\n .nr-artifact-card__icon {\n color: #c9d1d9;\n }\n .nr-artifact-card__title {\n color: #c9d1d9;\n }\n .nr-artifact-card__chevron {\n color: #8b949e;\n }\n }\n "}}
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 "}}
2915
2914
  /**
2916
2915
  * @license
2917
2916
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2926,7 +2925,7 @@ var Yt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
2926
2925
  * @license
2927
2926
  * Copyright 2023 Nuraly, Laabidi Aymen
2928
2927
  * SPDX-License-Identifier: MIT
2929
- */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 /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .${this.cssPrefix}__title {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__option {\n background: #2a2a2a;\n border-color: #444;\n }\n\n .${this.cssPrefix}__option:hover {\n border-color: #5a9aff;\n background: #1e2d44;\n box-shadow: 0 1px 4px rgba(90, 154, 255, 0.15);\n }\n\n .${this.cssPrefix}__option:active:not([aria-disabled="true"]) {\n background: #1a2638;\n }\n\n .${this.cssPrefix}__option-icon {\n color: #aaa;\n }\n\n .${this.cssPrefix}__option-label {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__option-description {\n color: #999;\n }\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 `}}
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 `}}
2930
2929
  /**
2931
2930
  * @license
2932
2931
  * Copyright 2023 Nuraly, Laabidi Aymen
@@ -2949,4 +2948,4 @@ var Yt=function(t,e,i,n){return new(i||(i=Promise))(function(o,s){function r(t){
2949
2948
  * Pipeline:
2950
2949
  * input blob β†’ AudioContext.decodeAudioData β†’ BufferSource β†’ MediaStreamDestination
2951
2950
  * β†’ MediaRecorder(ogg/opus, 32 kbps) β†’ output blob
2952
- */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,Fe 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,Dt 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,Ft 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};
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};