@nuraly/lumenui 0.2.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn.js +1 -0
- package/dist/nuralyui.bundle.js +3434 -2085
- package/dist/nuralyui.bundle.js.gz +0 -0
- package/dist/src/components/button/controllers/base.controller.d.ts +15 -0
- package/dist/src/components/button/controllers/base.controller.js +13 -0
- package/dist/src/components/button/controllers/index.d.ts +10 -0
- package/dist/src/components/button/controllers/index.js +10 -0
- package/dist/src/components/button/controllers/keyboard.controller.d.ts +32 -0
- package/dist/src/components/button/controllers/keyboard.controller.js +78 -0
- package/dist/src/components/button/controllers/link.controller.d.ts +30 -0
- package/dist/src/components/button/controllers/link.controller.js +75 -0
- package/dist/src/components/button/controllers/ripple.controller.d.ts +23 -0
- package/dist/src/components/button/controllers/ripple.controller.js +69 -0
- package/dist/src/components/button/interfaces/base-controller.interface.d.ts +61 -0
- package/dist/src/components/button/interfaces/base-controller.interface.js +7 -0
- package/dist/src/components/button/interfaces/index.d.ts +2 -0
- package/dist/src/components/button/interfaces/index.js +2 -0
- package/dist/src/components/button/test/nr-button_test.d.ts +2 -0
- package/dist/src/components/button/test/nr-button_test.js +91 -0
- package/dist/src/components/canvas/base-canvas.component.d.ts +2 -1
- package/dist/src/components/canvas/base-canvas.component.js +6 -0
- package/dist/src/components/canvas/bundle.js +1083 -491
- package/dist/src/components/canvas/bundle.js.gz +0 -0
- package/dist/src/components/canvas/canvas.constants.d.ts +1 -1
- package/dist/src/components/canvas/canvas.constants.js +1 -1
- package/dist/src/components/canvas/chatbot-panel.style.js +50 -59
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger-fields.component.d.ts +115 -0
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger-fields.component.js +480 -0
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger-fields.style.d.ts +7 -0
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger-fields.style.js +323 -0
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger.types.d.ts +162 -0
- package/dist/src/components/canvas/chatbot-trigger/chatbot-trigger.types.js +88 -0
- package/dist/src/components/canvas/chatbot-trigger/index.d.ts +9 -0
- package/dist/src/components/canvas/chatbot-trigger/index.js +12 -0
- package/dist/src/components/canvas/controllers/base.controller.d.ts +53 -0
- package/dist/src/components/canvas/controllers/base.controller.js +80 -0
- package/dist/src/components/canvas/controllers/clipboard.controller.d.ts +80 -0
- package/dist/src/components/canvas/controllers/clipboard.controller.js +300 -0
- package/dist/src/components/canvas/controllers/collaboration.controller.d.ts +54 -0
- package/dist/src/components/canvas/controllers/collaboration.controller.js +425 -0
- package/dist/src/components/canvas/controllers/config.controller.d.ts +61 -0
- package/dist/src/components/canvas/controllers/config.controller.js +118 -0
- package/dist/src/components/canvas/controllers/connection.controller.d.ts +69 -0
- package/dist/src/components/canvas/controllers/connection.controller.js +183 -0
- package/dist/src/components/canvas/controllers/drag.controller.d.ts +56 -0
- package/dist/src/components/canvas/controllers/drag.controller.js +195 -0
- package/dist/src/components/canvas/controllers/frame.controller.d.ts +94 -0
- package/dist/src/components/canvas/controllers/frame.controller.js +456 -0
- package/dist/src/components/canvas/controllers/index.d.ts +19 -0
- package/dist/src/components/canvas/controllers/index.js +32 -0
- package/dist/src/components/canvas/controllers/keyboard.controller.d.ts +44 -0
- package/dist/src/components/canvas/controllers/keyboard.controller.js +275 -0
- package/dist/src/components/canvas/controllers/marquee.controller.d.ts +71 -0
- package/dist/src/components/canvas/controllers/marquee.controller.js +128 -0
- package/dist/src/components/canvas/controllers/selection.controller.d.ts +85 -0
- package/dist/src/components/canvas/controllers/selection.controller.js +202 -0
- package/dist/src/components/canvas/controllers/touch.controller.d.ts +55 -0
- package/dist/src/components/canvas/controllers/touch.controller.js +299 -0
- package/dist/src/components/canvas/controllers/undo.controller.d.ts +100 -0
- package/dist/src/components/canvas/controllers/undo.controller.js +218 -0
- package/dist/src/components/canvas/controllers/viewport.controller.d.ts +91 -0
- package/dist/src/components/canvas/controllers/viewport.controller.js +287 -0
- package/dist/src/components/canvas/data-node/data-node-config.component.d.ts +67 -0
- package/dist/src/components/canvas/data-node/data-node-config.component.js +496 -0
- package/dist/src/components/canvas/data-node/data-node-fields.component.d.ts +198 -0
- package/dist/src/components/canvas/data-node/data-node-fields.component.js +931 -0
- package/dist/src/components/canvas/data-node/data-node-fields.style.d.ts +7 -0
- package/dist/src/components/canvas/data-node/data-node-fields.style.js +448 -0
- package/dist/src/components/canvas/data-node/data-node.types.d.ts +245 -0
- package/dist/src/components/canvas/data-node/data-node.types.js +158 -0
- package/dist/src/components/canvas/data-node/index.d.ts +9 -0
- package/dist/src/components/canvas/data-node/index.js +12 -0
- package/dist/src/components/canvas/data-node/schema-select.component.d.ts +36 -0
- package/dist/src/components/canvas/data-node/schema-select.component.js +196 -0
- package/dist/src/components/canvas/data-node/table-select.component.d.ts +38 -0
- package/dist/src/components/canvas/data-node/table-select.component.js +199 -0
- package/dist/src/components/canvas/interfaces/canvas-host.interface.d.ts +91 -0
- package/dist/src/components/canvas/interfaces/canvas-host.interface.js +7 -0
- package/dist/src/components/canvas/interfaces/collaboration.interface.d.ts +58 -0
- package/dist/src/components/canvas/interfaces/collaboration.interface.js +10 -0
- package/dist/src/components/canvas/interfaces/index.d.ts +8 -0
- package/dist/src/components/canvas/interfaces/index.js +7 -0
- package/dist/src/components/canvas/templates/chatbot-panel.template.d.ts +28 -0
- package/dist/src/components/canvas/templates/chatbot-panel.template.js +49 -0
- package/dist/src/components/canvas/templates/config-panel.template.d.ts +22 -0
- package/dist/src/components/canvas/templates/config-panel.template.js +22 -0
- package/dist/src/components/canvas/templates/context-menu.template.d.ts +30 -0
- package/dist/src/components/canvas/templates/context-menu.template.js +80 -0
- package/dist/src/components/canvas/templates/edges.template.d.ts +41 -0
- package/dist/src/components/canvas/templates/edges.template.js +243 -0
- package/dist/src/components/canvas/templates/empty-state.template.d.ts +17 -0
- package/dist/src/components/canvas/templates/empty-state.template.js +25 -0
- package/dist/src/components/canvas/templates/frame.template.d.ts +24 -0
- package/dist/src/components/canvas/templates/frame.template.js +74 -0
- package/dist/src/components/canvas/templates/index.d.ts +18 -0
- package/dist/src/components/canvas/templates/index.js +30 -0
- package/dist/src/components/canvas/templates/palette.template.d.ts +27 -0
- package/dist/src/components/canvas/templates/palette.template.js +110 -0
- package/dist/src/components/canvas/templates/presence-bar.template.d.ts +18 -0
- package/dist/src/components/canvas/templates/presence-bar.template.js +60 -0
- package/dist/src/components/canvas/templates/remote-cursors.template.d.ts +19 -0
- package/dist/src/components/canvas/templates/remote-cursors.template.js +43 -0
- package/dist/src/components/canvas/templates/toolbar.template.d.ts +52 -0
- package/dist/src/components/canvas/templates/toolbar.template.js +118 -0
- package/dist/src/components/canvas/templates/wb-floating-toolbar.template.d.ts +30 -0
- package/dist/src/components/canvas/templates/wb-floating-toolbar.template.js +219 -0
- package/dist/src/components/canvas/templates/wb-sidebar.template.d.ts +23 -0
- package/dist/src/components/canvas/templates/wb-sidebar.template.js +152 -0
- package/dist/src/components/canvas/utils/variable-resolver.d.ts +71 -0
- package/dist/src/components/canvas/utils/variable-resolver.js +280 -0
- package/dist/src/components/canvas/workflow-canvas.component.d.ts +7 -0
- package/dist/src/components/canvas/workflow-canvas.component.js +52 -2
- package/dist/src/components/canvas/workflow-canvas.style.js +46 -55
- package/dist/src/components/canvas/workflow-canvas.types.d.ts +8 -1
- package/dist/src/components/canvas/workflow-canvas.types.js +157 -0
- package/dist/src/components/carousel/demo/carousel-demo.d.ts +6 -0
- package/dist/src/components/carousel/demo/carousel-demo.js +68 -0
- package/dist/src/components/chat-panel/bundle.js +216 -0
- package/dist/src/components/chat-panel/bundle.js.gz +0 -0
- package/dist/src/components/chat-panel/chat-panel.component.d.ts +85 -0
- package/dist/src/components/chat-panel/chat-panel.component.js +510 -0
- package/dist/src/components/chat-panel/chat-panel.style.d.ts +2 -0
- package/dist/src/components/chat-panel/chat-panel.style.js +127 -0
- package/dist/src/components/chat-panel/chat-panel.types.d.ts +54 -0
- package/dist/src/components/chat-panel/chat-panel.types.js +2 -0
- package/dist/src/components/chat-panel/index.d.ts +3 -0
- package/dist/src/components/chat-panel/index.js +2 -0
- package/dist/src/components/chatbot/audio-compress.d.ts +26 -0
- package/dist/src/components/chatbot/audio-compress.js +84 -0
- package/dist/src/components/chatbot/bundle.js +388 -144
- package/dist/src/components/chatbot/bundle.js.gz +0 -0
- package/dist/src/components/chatbot/chatbot-audio.controller.d.ts +35 -0
- package/dist/src/components/chatbot/chatbot-audio.controller.js +160 -0
- package/dist/src/components/chatbot/chatbot.component.d.ts +12 -0
- package/dist/src/components/chatbot/chatbot.component.js +41 -2
- package/dist/src/components/chatbot/chatbot.style.js +141 -0
- package/dist/src/components/chatbot/chatbot.types.d.ts +8 -0
- package/dist/src/components/chatbot/controllers/index.d.ts +8 -0
- package/dist/src/components/chatbot/controllers/index.js +8 -0
- package/dist/src/components/chatbot/controllers/scroll.controller.d.ts +34 -0
- package/dist/src/components/chatbot/controllers/scroll.controller.js +43 -0
- package/dist/src/components/chatbot/core/chatbot-core.controller.d.ts +283 -0
- package/dist/src/components/chatbot/core/chatbot-core.controller.js +824 -0
- package/dist/src/components/chatbot/core/event-bus.d.ts +54 -0
- package/dist/src/components/chatbot/core/event-bus.js +102 -0
- package/dist/src/components/chatbot/core/index.d.ts +12 -0
- package/dist/src/components/chatbot/core/index.js +15 -0
- package/dist/src/components/chatbot/core/types.d.ts +403 -0
- package/dist/src/components/chatbot/core/types.js +16 -0
- package/dist/src/components/chatbot/locales/locale-codes.d.ts +14 -0
- package/dist/src/components/chatbot/locales/locale-codes.js +23 -0
- package/dist/src/components/chatbot/plugins/analytics-plugin.d.ts +23 -0
- package/dist/src/components/chatbot/plugins/analytics-plugin.js +52 -0
- package/dist/src/components/chatbot/plugins/artifact-plugin.d.ts +71 -0
- package/dist/src/components/chatbot/plugins/artifact-plugin.js +313 -0
- package/dist/src/components/chatbot/plugins/chat-plugin.d.ts +44 -0
- package/dist/src/components/chatbot/plugins/chat-plugin.js +58 -0
- package/dist/src/components/chatbot/plugins/flight-card-plugin.d.ts +116 -0
- package/dist/src/components/chatbot/plugins/flight-card-plugin.js +594 -0
- package/dist/src/components/chatbot/plugins/flow-diagram-plugin.d.ts +23 -0
- package/dist/src/components/chatbot/plugins/flow-diagram-plugin.js +495 -0
- package/dist/src/components/chatbot/plugins/index.d.ts +16 -0
- package/dist/src/components/chatbot/plugins/index.js +17 -0
- package/dist/src/components/chatbot/plugins/json-graph-renderer-plugin.d.ts +43 -0
- package/dist/src/components/chatbot/plugins/json-graph-renderer-plugin.js +166 -0
- package/dist/src/components/chatbot/plugins/markdown-plugin.d.ts +26 -0
- package/dist/src/components/chatbot/plugins/markdown-plugin.js +68 -0
- package/dist/src/components/chatbot/plugins/persistence-plugin.d.ts +30 -0
- package/dist/src/components/chatbot/plugins/persistence-plugin.js +91 -0
- package/dist/src/components/chatbot/plugins/print-job-card-plugin.d.ts +110 -0
- package/dist/src/components/chatbot/plugins/print-job-card-plugin.js +505 -0
- package/dist/src/components/chatbot/plugins/selection-card-plugin.d.ts +111 -0
- package/dist/src/components/chatbot/plugins/selection-card-plugin.js +318 -0
- package/dist/src/components/chatbot/providers/custom-api-provider.d.ts +63 -0
- package/dist/src/components/chatbot/providers/custom-api-provider.js +240 -0
- package/dist/src/components/chatbot/providers/index.d.ts +16 -0
- package/dist/src/components/chatbot/providers/index.js +13 -0
- package/dist/src/components/chatbot/providers/mock-provider.d.ts +154 -0
- package/dist/src/components/chatbot/providers/mock-provider.js +411 -0
- package/dist/src/components/chatbot/providers/native-ws-provider.d.ts +184 -0
- package/dist/src/components/chatbot/providers/native-ws-provider.js +544 -0
- package/dist/src/components/chatbot/providers/openai-provider.d.ts +32 -0
- package/dist/src/components/chatbot/providers/openai-provider.js +246 -0
- package/dist/src/components/chatbot/providers/socket-provider.d.ts +159 -0
- package/dist/src/components/chatbot/providers/socket-provider.js +390 -0
- package/dist/src/components/chatbot/providers/workflow-socket-provider.d.ts +116 -0
- package/dist/src/components/chatbot/providers/workflow-socket-provider.js +484 -0
- package/dist/src/components/chatbot/storage/index.d.ts +7 -0
- package/dist/src/components/chatbot/storage/index.js +8 -0
- package/dist/src/components/chatbot/storage/storage-implementations.d.ts +43 -0
- package/dist/src/components/chatbot/storage/storage-implementations.js +179 -0
- package/dist/src/components/chatbot/templates/artifact-panel.template.d.ts +22 -0
- package/dist/src/components/chatbot/templates/artifact-panel.template.js +81 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.d.ts +49 -0
- package/dist/src/components/chatbot/templates/chatbot-main.template.js +115 -0
- package/dist/src/components/chatbot/templates/file-preview-modal.template.d.ts +19 -0
- package/dist/src/components/chatbot/templates/file-preview-modal.template.js +74 -0
- package/dist/src/components/chatbot/templates/file-upload-area.template.d.ts +19 -0
- package/dist/src/components/chatbot/templates/file-upload-area.template.js +29 -0
- package/dist/src/components/chatbot/templates/index.d.ts +15 -0
- package/dist/src/components/chatbot/templates/index.js +15 -0
- package/dist/src/components/chatbot/templates/input-box.template.d.ts +49 -0
- package/dist/src/components/chatbot/templates/input-box.template.js +317 -0
- package/dist/src/components/chatbot/templates/message.template.d.ts +31 -0
- package/dist/src/components/chatbot/templates/message.template.js +214 -0
- package/dist/src/components/chatbot/templates/suggestion.template.d.ts +20 -0
- package/dist/src/components/chatbot/templates/suggestion.template.js +40 -0
- package/dist/src/components/chatbot/templates/thread-sidebar.template.d.ts +24 -0
- package/dist/src/components/chatbot/templates/thread-sidebar.template.js +160 -0
- package/dist/src/components/chatbot/templates/url-modal.template.d.ts +25 -0
- package/dist/src/components/chatbot/templates/url-modal.template.js +100 -0
- package/dist/src/components/chatbot/utils/format.d.ts +23 -0
- package/dist/src/components/chatbot/utils/format.js +84 -0
- package/dist/src/components/chatbot/utils/index.d.ts +7 -0
- package/dist/src/components/chatbot/utils/index.js +7 -0
- package/dist/src/components/checkbox/mixins/checkbox-event-mixin.d.ts +87 -0
- package/dist/src/components/checkbox/mixins/checkbox-event-mixin.js +94 -0
- package/dist/src/components/checkbox/mixins/checkbox-focus-mixin.d.ts +55 -0
- package/dist/src/components/checkbox/mixins/checkbox-focus-mixin.js +57 -0
- package/dist/src/components/checkbox/mixins/index.d.ts +10 -0
- package/dist/src/components/checkbox/mixins/index.js +8 -0
- package/dist/src/components/checkbox/test/checkbox_test.d.ts +2 -0
- package/dist/src/components/checkbox/test/checkbox_test.js +88 -0
- package/dist/src/components/collapse/controllers/accordion.controller.d.ts +60 -0
- package/dist/src/components/collapse/controllers/accordion.controller.js +132 -0
- package/dist/src/components/collapse/controllers/animation.controller.d.ts +40 -0
- package/dist/src/components/collapse/controllers/animation.controller.js +125 -0
- package/dist/src/components/collapse/controllers/base.controller.d.ts +48 -0
- package/dist/src/components/collapse/controllers/base.controller.js +69 -0
- package/dist/src/components/collapse/controllers/index.d.ts +12 -0
- package/dist/src/components/collapse/controllers/index.js +11 -0
- package/dist/src/components/collapse/controllers/keyboard.controller.d.ts +73 -0
- package/dist/src/components/collapse/controllers/keyboard.controller.js +186 -0
- package/dist/src/components/colorpicker/controllers/base.controller.d.ts +14 -0
- package/dist/src/components/colorpicker/controllers/base.controller.js +15 -0
- package/dist/src/components/colorpicker/controllers/dropdown.controller.d.ts +60 -0
- package/dist/src/components/colorpicker/controllers/dropdown.controller.js +243 -0
- package/dist/src/components/colorpicker/controllers/event.controller.d.ts +46 -0
- package/dist/src/components/colorpicker/controllers/event.controller.js +130 -0
- package/dist/src/components/colorpicker/controllers/index.d.ts +4 -0
- package/dist/src/components/colorpicker/controllers/index.js +4 -0
- package/dist/src/components/colorpicker/interfaces/index.d.ts +60 -0
- package/dist/src/components/colorpicker/interfaces/index.js +2 -0
- package/dist/src/components/datepicker/controllers/calendar.controller.d.ts +78 -0
- package/dist/src/components/datepicker/controllers/calendar.controller.js +225 -0
- package/dist/src/components/datepicker/controllers/index.d.ts +11 -0
- package/dist/src/components/datepicker/controllers/index.js +11 -0
- package/dist/src/components/datepicker/controllers/keyboard.controller.d.ts +96 -0
- package/dist/src/components/datepicker/controllers/keyboard.controller.js +246 -0
- package/dist/src/components/datepicker/controllers/month-year-dropdown.controller.d.ts +48 -0
- package/dist/src/components/datepicker/controllers/month-year-dropdown.controller.js +92 -0
- package/dist/src/components/datepicker/controllers/positioning.controller.d.ts +82 -0
- package/dist/src/components/datepicker/controllers/positioning.controller.js +247 -0
- package/dist/src/components/datepicker/controllers/selection.controller.d.ts +92 -0
- package/dist/src/components/datepicker/controllers/selection.controller.js +267 -0
- package/dist/src/components/datepicker/interfaces/base-controller.interface.d.ts +40 -0
- package/dist/src/components/datepicker/interfaces/base-controller.interface.js +7 -0
- package/dist/src/components/datepicker/interfaces/datepicker-controllers.interface.d.ts +112 -0
- package/dist/src/components/datepicker/interfaces/datepicker-controllers.interface.js +7 -0
- package/dist/src/components/datepicker/interfaces/index.d.ts +8 -0
- package/dist/src/components/datepicker/interfaces/index.js +7 -0
- package/dist/src/components/datepicker/templates/days.template.d.ts +4 -0
- package/dist/src/components/datepicker/templates/days.template.js +40 -0
- package/dist/src/components/datepicker/templates/dropdown.template.d.ts +10 -0
- package/dist/src/components/datepicker/templates/dropdown.template.js +50 -0
- package/dist/src/components/datepicker/templates/headers.template.d.ts +2 -0
- package/dist/src/components/datepicker/templates/headers.template.js +5 -0
- package/dist/src/components/datepicker/templates/months.template.d.ts +6 -0
- package/dist/src/components/datepicker/templates/months.template.js +10 -0
- package/dist/src/components/datepicker/templates/years.template.d.ts +6 -0
- package/dist/src/components/datepicker/templates/years.template.js +11 -0
- package/dist/src/components/datepicker/test/datepicker_test.d.ts +2 -0
- package/dist/src/components/datepicker/test/datepicker_test.js +134 -0
- package/dist/src/components/datepicker/utils/day.helper.d.ts +5 -0
- package/dist/src/components/datepicker/utils/day.helper.js +53 -0
- package/dist/src/components/datepicker/utils/formatter.d.ts +2 -0
- package/dist/src/components/datepicker/utils/formatter.js +9 -0
- package/dist/src/components/datepicker/utils/index.d.ts +11 -0
- package/dist/src/components/datepicker/utils/index.js +11 -0
- package/dist/src/components/datepicker/utils/locale.helper.d.ts +144 -0
- package/dist/src/components/datepicker/utils/locale.helper.js +151 -0
- package/dist/src/components/datepicker/utils/month.helper.d.ts +3 -0
- package/dist/src/components/datepicker/utils/month.helper.js +24 -0
- package/dist/src/components/datepicker/utils/string.helper.d.ts +2 -0
- package/dist/src/components/datepicker/utils/string.helper.js +4 -0
- package/dist/src/components/document/demo/document-demo.d.ts +12 -0
- package/dist/src/components/document/demo/document-demo.js +40 -0
- package/dist/src/components/dropdown/controllers/base.controller.d.ts +18 -0
- package/dist/src/components/dropdown/controllers/base.controller.js +22 -0
- package/dist/src/components/dropdown/controllers/dropdown.controller.d.ts +50 -0
- package/dist/src/components/dropdown/controllers/dropdown.controller.js +408 -0
- package/dist/src/components/dropdown/controllers/index.d.ts +3 -0
- package/dist/src/components/dropdown/controllers/index.js +3 -0
- package/dist/src/components/dropdown/interfaces/controller-interfaces.d.ts +79 -0
- package/dist/src/components/dropdown/interfaces/controller-interfaces.js +2 -0
- package/dist/src/components/dropdown/interfaces/index.d.ts +2 -0
- package/dist/src/components/dropdown/interfaces/index.js +2 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-item.d.ts +12 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-item.js +55 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-item.style.d.ts +2 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-item.style.js +34 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-menu.d.ts +18 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-menu.js +70 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-menu.style.d.ts +2 -0
- package/dist/src/components/dropdown/templates/nr-dropdown-menu.style.js +49 -0
- package/dist/src/components/file-upload/demo/file-upload-demo.d.ts +18 -0
- package/dist/src/components/file-upload/demo/file-upload-demo.js +156 -0
- package/dist/src/components/form/controllers/submission.controller.d.ts +60 -0
- package/dist/src/components/form/controllers/submission.controller.js +220 -0
- package/dist/src/components/form/controllers/validation.controller.d.ts +87 -0
- package/dist/src/components/form/controllers/validation.controller.js +236 -0
- package/dist/src/components/form/interfaces/validation.interface.d.ts +118 -0
- package/dist/src/components/form/interfaces/validation.interface.js +7 -0
- package/dist/src/components/icon/mixins/clickable-mixin.d.ts +57 -0
- package/dist/src/components/icon/mixins/clickable-mixin.js +111 -0
- package/dist/src/components/icon/mixins/index.d.ts +7 -0
- package/dist/src/components/icon/mixins/index.js +7 -0
- package/dist/src/components/iconpicker/controllers/event.controller.d.ts +38 -0
- package/dist/src/components/iconpicker/controllers/event.controller.js +68 -0
- package/dist/src/components/iconpicker/controllers/index.d.ts +9 -0
- package/dist/src/components/iconpicker/controllers/index.js +9 -0
- package/dist/src/components/iconpicker/controllers/search.controller.d.ts +34 -0
- package/dist/src/components/iconpicker/controllers/search.controller.js +55 -0
- package/dist/src/components/iconpicker/controllers/selection.controller.d.ts +27 -0
- package/dist/src/components/iconpicker/controllers/selection.controller.js +39 -0
- package/dist/src/components/iconpicker/interfaces/icon-picker.interface.d.ts +13 -0
- package/dist/src/components/iconpicker/interfaces/icon-picker.interface.js +7 -0
- package/dist/src/components/iconpicker/interfaces/index.d.ts +7 -0
- package/dist/src/components/iconpicker/interfaces/index.js +7 -0
- package/dist/src/components/iconpicker/utils/icon-filter.utils.d.ts +29 -0
- package/dist/src/components/iconpicker/utils/icon-filter.utils.js +96 -0
- package/dist/src/components/iconpicker/utils/icon-loader.utils.d.ts +39 -0
- package/dist/src/components/iconpicker/utils/icon-loader.utils.js +115 -0
- package/dist/src/components/iconpicker/utils/index.d.ts +8 -0
- package/dist/src/components/iconpicker/utils/index.js +8 -0
- package/dist/src/components/iconpicker/utils/lucide-icons.d.ts +10 -0
- package/dist/src/components/iconpicker/utils/lucide-icons.js +1624 -0
- package/dist/src/components/input/controllers/base.controller.d.ts +35 -0
- package/dist/src/components/input/controllers/base.controller.js +13 -0
- package/dist/src/components/input/controllers/event.controller.d.ts +111 -0
- package/dist/src/components/input/controllers/event.controller.js +355 -0
- package/dist/src/components/input/controllers/index.d.ts +14 -0
- package/dist/src/components/input/controllers/index.js +10 -0
- package/dist/src/components/input/controllers/state.controller.d.ts +153 -0
- package/dist/src/components/input/controllers/state.controller.js +245 -0
- package/dist/src/components/input/controllers/validation.controller.d.ts +205 -0
- package/dist/src/components/input/controllers/validation.controller.js +698 -0
- package/dist/src/components/input/mixins/focus-mixin.d.ts +60 -0
- package/dist/src/components/input/mixins/focus-mixin.js +65 -0
- package/dist/src/components/input/mixins/index.d.ts +12 -0
- package/dist/src/components/input/mixins/index.js +9 -0
- package/dist/src/components/input/mixins/number-mixin.d.ts +51 -0
- package/dist/src/components/input/mixins/number-mixin.js +128 -0
- package/dist/src/components/input/mixins/selection-mixin.d.ts +57 -0
- package/dist/src/components/input/mixins/selection-mixin.js +80 -0
- package/dist/src/components/input/test/nr-input_test.d.ts +2 -0
- package/dist/src/components/input/test/nr-input_test.js +159 -0
- package/dist/src/components/input/utils/index.d.ts +8 -0
- package/dist/src/components/input/utils/index.js +8 -0
- package/dist/src/components/input/utils/input-renderers.d.ts +54 -0
- package/dist/src/components/input/utils/input-renderers.js +178 -0
- package/dist/src/components/input/utils/input-validation.utils.d.ts +26 -0
- package/dist/src/components/input/utils/input-validation.utils.js +103 -0
- package/dist/src/components/menu/controllers/accessibility.controller.d.ts +86 -0
- package/dist/src/components/menu/controllers/accessibility.controller.js +235 -0
- package/dist/src/components/menu/controllers/base.controller.d.ts +41 -0
- package/dist/src/components/menu/controllers/base.controller.js +61 -0
- package/dist/src/components/menu/controllers/index.d.ts +10 -0
- package/dist/src/components/menu/controllers/index.js +10 -0
- package/dist/src/components/menu/controllers/keyboard.controller.d.ts +84 -0
- package/dist/src/components/menu/controllers/keyboard.controller.js +328 -0
- package/dist/src/components/menu/controllers/state.controller.d.ts +106 -0
- package/dist/src/components/menu/controllers/state.controller.js +249 -0
- package/dist/src/components/menu/interfaces/controller.interface.d.ts +51 -0
- package/dist/src/components/menu/interfaces/controller.interface.js +7 -0
- package/dist/src/components/menu/interfaces/index.d.ts +7 -0
- package/dist/src/components/menu/interfaces/index.js +7 -0
- package/dist/src/components/modal/controllers/index.d.ts +8 -0
- package/dist/src/components/modal/controllers/index.js +8 -0
- package/dist/src/components/modal/controllers/modal-drag-controller.d.ts +39 -0
- package/dist/src/components/modal/controllers/modal-drag-controller.js +108 -0
- package/dist/src/components/modal/controllers/modal-keyboard-controller.d.ts +36 -0
- package/dist/src/components/modal/controllers/modal-keyboard-controller.js +128 -0
- package/dist/src/components/panel/controllers/index.d.ts +8 -0
- package/dist/src/components/panel/controllers/index.js +8 -0
- package/dist/src/components/panel/controllers/panel-drag-controller.d.ts +40 -0
- package/dist/src/components/panel/controllers/panel-drag-controller.js +118 -0
- package/dist/src/components/panel/controllers/panel-resize-controller.d.ts +37 -0
- package/dist/src/components/panel/controllers/panel-resize-controller.js +124 -0
- package/dist/src/components/presence/bundle.js +555 -0
- package/dist/src/components/presence/bundle.js.gz +0 -0
- package/dist/src/components/presence/index.d.ts +10 -0
- package/dist/src/components/presence/index.js +10 -0
- package/dist/src/components/presence/presence-avatars.component.d.ts +40 -0
- package/dist/src/components/presence/presence-avatars.component.js +83 -0
- package/dist/src/components/presence/presence-avatars.style.d.ts +7 -0
- package/dist/src/components/presence/presence-avatars.style.js +105 -0
- package/dist/src/components/presence/presence-chat.component.d.ts +55 -0
- package/dist/src/components/presence/presence-chat.component.js +238 -0
- package/dist/src/components/presence/presence-chat.style.d.ts +7 -0
- package/dist/src/components/presence/presence-chat.style.js +248 -0
- package/dist/src/components/presence/presence.component.d.ts +95 -0
- package/dist/src/components/presence/presence.component.js +510 -0
- package/dist/src/components/presence/presence.style.d.ts +7 -0
- package/dist/src/components/presence/presence.style.js +12 -0
- package/dist/src/components/presence/presence.types.d.ts +33 -0
- package/dist/src/components/presence/presence.types.js +7 -0
- package/dist/src/components/presence/react.d.ts +24 -0
- package/dist/src/components/presence/react.js +41 -0
- package/dist/src/components/radio-group/controllers/focus.controller.d.ts +98 -0
- package/dist/src/components/radio-group/controllers/focus.controller.js +216 -0
- package/dist/src/components/radio-group/controllers/group.controller.d.ts +140 -0
- package/dist/src/components/radio-group/controllers/group.controller.js +179 -0
- package/dist/src/components/radio-group/controllers/index.d.ts +11 -0
- package/dist/src/components/radio-group/controllers/index.js +11 -0
- package/dist/src/components/radio-group/controllers/keyboard.controller.d.ts +24 -0
- package/dist/src/components/radio-group/controllers/keyboard.controller.js +93 -0
- package/dist/src/components/radio-group/controllers/ripple.controller.d.ts +59 -0
- package/dist/src/components/radio-group/controllers/ripple.controller.js +208 -0
- package/dist/src/components/radio-group/controllers/validation.controller.d.ts +73 -0
- package/dist/src/components/radio-group/controllers/validation.controller.js +108 -0
- package/dist/src/components/radio-group/interfaces/base-controller.interface.d.ts +75 -0
- package/dist/src/components/radio-group/interfaces/base-controller.interface.js +7 -0
- package/dist/src/components/radio-group/interfaces/focus-controller.interface.d.ts +40 -0
- package/dist/src/components/radio-group/interfaces/focus-controller.interface.js +7 -0
- package/dist/src/components/radio-group/interfaces/index.d.ts +11 -0
- package/dist/src/components/radio-group/interfaces/index.js +7 -0
- package/dist/src/components/radio-group/interfaces/ripple-controller.interface.d.ts +31 -0
- package/dist/src/components/radio-group/interfaces/ripple-controller.interface.js +7 -0
- package/dist/src/components/radio-group/interfaces/selection-controller.interface.d.ts +45 -0
- package/dist/src/components/radio-group/interfaces/selection-controller.interface.js +7 -0
- package/dist/src/components/radio-group/interfaces/validation-controller.interface.d.ts +48 -0
- package/dist/src/components/radio-group/interfaces/validation-controller.interface.js +7 -0
- package/dist/src/components/radio-group/test/radio_test.d.ts +2 -0
- package/dist/src/components/radio-group/test/radio_test.js +79 -0
- package/dist/src/components/select/controllers/base.controller.d.ts +10 -0
- package/dist/src/components/select/controllers/base.controller.js +8 -0
- package/dist/src/components/select/controllers/dropdown.controller.d.ts +76 -0
- package/dist/src/components/select/controllers/dropdown.controller.js +281 -0
- package/dist/src/components/select/controllers/event.controller.d.ts +54 -0
- package/dist/src/components/select/controllers/event.controller.js +113 -0
- package/dist/src/components/select/controllers/focus.controller.d.ts +79 -0
- package/dist/src/components/select/controllers/focus.controller.js +230 -0
- package/dist/src/components/select/controllers/index.d.ts +9 -0
- package/dist/src/components/select/controllers/index.js +9 -0
- package/dist/src/components/select/controllers/keyboard.controller.d.ts +75 -0
- package/dist/src/components/select/controllers/keyboard.controller.js +369 -0
- package/dist/src/components/select/controllers/search.controller.d.ts +71 -0
- package/dist/src/components/select/controllers/search.controller.js +167 -0
- package/dist/src/components/select/controllers/selection.controller.d.ts +67 -0
- package/dist/src/components/select/controllers/selection.controller.js +217 -0
- package/dist/src/components/select/controllers/validation.controller.d.ts +66 -0
- package/dist/src/components/select/controllers/validation.controller.js +189 -0
- package/dist/src/components/select/interfaces/base-controller.interface.d.ts +147 -0
- package/dist/src/components/select/interfaces/base-controller.interface.js +2 -0
- package/dist/src/components/select/interfaces/controller-interfaces.d.ts +94 -0
- package/dist/src/components/select/interfaces/controller-interfaces.js +11 -0
- package/dist/src/components/select/interfaces/index.d.ts +3 -0
- package/dist/src/components/select/interfaces/index.js +3 -0
- package/dist/src/components/slider-input/utils/debounce.d.ts +2 -0
- package/dist/src/components/slider-input/utils/debounce.js +8 -0
- package/dist/src/components/slider-input/utils/index.d.ts +2 -0
- package/dist/src/components/slider-input/utils/index.js +2 -0
- package/dist/src/components/table/controllers/base.controller.d.ts +15 -0
- package/dist/src/components/table/controllers/base.controller.js +13 -0
- package/dist/src/components/table/controllers/filter.controller.d.ts +48 -0
- package/dist/src/components/table/controllers/filter.controller.js +152 -0
- package/dist/src/components/table/controllers/index.d.ts +11 -0
- package/dist/src/components/table/controllers/index.js +11 -0
- package/dist/src/components/table/controllers/pagination.controller.d.ts +36 -0
- package/dist/src/components/table/controllers/pagination.controller.js +110 -0
- package/dist/src/components/table/controllers/selection.controller.d.ts +40 -0
- package/dist/src/components/table/controllers/selection.controller.js +120 -0
- package/dist/src/components/table/controllers/sort.controller.d.ts +32 -0
- package/dist/src/components/table/controllers/sort.controller.js +102 -0
- package/dist/src/components/table/interfaces/index.d.ts +7 -0
- package/dist/src/components/table/interfaces/index.js +7 -0
- package/dist/src/components/table/interfaces/table-host.interface.d.ts +48 -0
- package/dist/src/components/table/interfaces/table-host.interface.js +7 -0
- package/dist/src/components/table/templates/actions.template.d.ts +14 -0
- package/dist/src/components/table/templates/actions.template.js +15 -0
- package/dist/src/components/table/templates/column-filter.template.d.ts +24 -0
- package/dist/src/components/table/templates/column-filter.template.js +76 -0
- package/dist/src/components/table/templates/content.template.d.ts +37 -0
- package/dist/src/components/table/templates/content.template.js +208 -0
- package/dist/src/components/table/templates/empty.template.d.ts +8 -0
- package/dist/src/components/table/templates/empty.template.js +47 -0
- package/dist/src/components/table/templates/filter.template.d.ts +14 -0
- package/dist/src/components/table/templates/filter.template.js +28 -0
- package/dist/src/components/table/templates/index.d.ts +8 -0
- package/dist/src/components/table/templates/index.js +8 -0
- package/dist/src/components/table/templates/loading.template.d.ts +21 -0
- package/dist/src/components/table/templates/loading.template.js +51 -0
- package/dist/src/components/table/templates/pagination.template.d.ts +24 -0
- package/dist/src/components/table/templates/pagination.template.js +52 -0
- package/dist/src/components/tabs/controllers/base.controller.d.ts +49 -0
- package/dist/src/components/tabs/controllers/base.controller.js +26 -0
- package/dist/src/components/tabs/controllers/dragdrop.controller.d.ts +84 -0
- package/dist/src/components/tabs/controllers/dragdrop.controller.js +202 -0
- package/dist/src/components/tabs/controllers/editable.controller.d.ts +100 -0
- package/dist/src/components/tabs/controllers/editable.controller.js +242 -0
- package/dist/src/components/tabs/controllers/event.controller.d.ts +104 -0
- package/dist/src/components/tabs/controllers/event.controller.js +239 -0
- package/dist/src/components/tabs/controllers/index.d.ts +12 -0
- package/dist/src/components/tabs/controllers/index.js +18 -0
- package/dist/src/components/tabs/controllers/keyboard.controller.d.ts +85 -0
- package/dist/src/components/tabs/controllers/keyboard.controller.js +233 -0
- package/dist/src/components/tabs/controllers/popout.controller.d.ts +96 -0
- package/dist/src/components/tabs/controllers/popout.controller.js +441 -0
- package/dist/src/components/textarea/controllers/base.controller.d.ts +43 -0
- package/dist/src/components/textarea/controllers/base.controller.js +19 -0
- package/dist/src/components/textarea/controllers/event.controller.d.ts +169 -0
- package/dist/src/components/textarea/controllers/event.controller.js +408 -0
- package/dist/src/components/textarea/controllers/index.d.ts +9 -0
- package/dist/src/components/textarea/controllers/index.js +9 -0
- package/dist/src/components/textarea/controllers/validation.controller.d.ts +133 -0
- package/dist/src/components/textarea/controllers/validation.controller.js +315 -0
- package/dist/src/components/timepicker/controllers/formatting.controller.d.ts +93 -0
- package/dist/src/components/timepicker/controllers/formatting.controller.js +195 -0
- package/dist/src/components/timepicker/controllers/index.d.ts +9 -0
- package/dist/src/components/timepicker/controllers/index.js +9 -0
- package/dist/src/components/timepicker/controllers/selection.controller.d.ts +72 -0
- package/dist/src/components/timepicker/controllers/selection.controller.js +175 -0
- package/dist/src/components/timepicker/controllers/validation.controller.d.ts +88 -0
- package/dist/src/components/timepicker/controllers/validation.controller.js +200 -0
- package/dist/src/components/timepicker/interfaces/timepicker.interface.d.ts +103 -0
- package/dist/src/components/timepicker/interfaces/timepicker.interface.js +7 -0
- package/dist/src/components/timepicker/test/timepicker_test.d.ts +7 -0
- package/dist/src/components/timepicker/test/timepicker_test.js +218 -0
- package/dist/src/components/timepicker/utils/time.utils.d.ts +87 -0
- package/dist/src/components/timepicker/utils/time.utils.js +235 -0
- package/dist/src/components/toast/bundle.js +11 -9
- package/dist/src/components/toast/bundle.js.gz +0 -0
- package/dist/src/components/toast/controllers/base.controller.d.ts +20 -0
- package/dist/src/components/toast/controllers/base.controller.js +12 -0
- package/dist/src/components/toast/controllers/index.d.ts +8 -0
- package/dist/src/components/toast/controllers/index.js +7 -0
- package/dist/src/components/toast/toast.component.d.ts +8 -0
- package/dist/src/components/toast/toast.component.js +17 -7
- package/dist/src/components/tooltips/demo/tooltips-demo.d.ts +18 -0
- package/dist/src/components/tooltips/demo/tooltips-demo.js +132 -0
- package/dist/src/components/tooltips/test/tooltips_test.d.ts +2 -0
- package/dist/src/components/tooltips/test/tooltips_test.js +145 -0
- package/dist/src/components/video/bundle.js +13 -12
- package/dist/src/components/video/bundle.js.gz +0 -0
- package/dist/src/components/video/video.component.d.ts +15 -1
- package/dist/src/components/video/video.component.js +131 -3
- package/package.json +31 -10
- package/packages/common/dist/VERSIONS.md +1 -1
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import{css as t,nothing as e,html as n,LitElement as i}from"lit";import{property as o,state as s,customElement as r}from"lit/decorators.js";import{classMap as a}from"lit/directives/class-map.js";import{unsafeHTML as l}from"lit/directives/unsafe-html.js";import{repeat as
|
|
1
|
+
import{css as t,nothing as e,html as n,LitElement as i}from"lit";import{property as o,state as s,customElement as r}from"lit/decorators.js";import{classMap as a}from"lit/directives/class-map.js";import{unsafeHTML as l}from"lit/directives/unsafe-html.js";import{repeat as c}from"lit/directives/repeat.js";import{styleMap as d}from"lit/directives/style-map.js";import{io as h}from"socket.io-client";
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2021 Google LLC
|
|
5
5
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
6
|
-
*/const
|
|
6
|
+
*/const u="lit-localize-status",p=(t,e,n)=>{let i=t[0];for(let o=1;o<t.length;o++)i+=e[n?n[o-1]:o-1],i+=t[o];return i},f=t=>{return"string"!=typeof(e=t)&&"strTag"in e?p(t.strings,t.values):t;var e};
|
|
7
7
|
/**
|
|
8
8
|
* @license
|
|
9
9
|
* Copyright 2021 Google LLC
|
|
10
10
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
11
|
-
*/let f
|
|
11
|
+
*/let g=f,m=!1;
|
|
12
12
|
/**
|
|
13
13
|
* @license
|
|
14
14
|
* Copyright 2021 Google LLC
|
|
15
15
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
16
16
|
*/
|
|
17
|
-
class
|
|
17
|
+
class v{constructor(t){this.t=t=>{"ready"===t.detail.status&&this.host.requestUpdate()},this.host=t}hostConnected(){window.addEventListener(u,this.t)}hostDisconnected(){window.removeEventListener(u,this.t)}}const b=t=>t.addController(new v(t));
|
|
18
18
|
/**
|
|
19
19
|
* @license
|
|
20
20
|
* Copyright 2020 Google LLC
|
|
21
21
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
22
22
|
*/
|
|
23
|
-
class
|
|
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
|
|
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,n=8997,i=0,o=33826,s=0,r=40164,a=0,l=52210;for(let c=0;c<t.length;c++)n^=t.charCodeAt(c),e=435*n,i=435*o,s=435*r,a=435*l,s+=n<<8,a+=o<<8,i+=e>>>16,n=65535&e,s+=i>>>16,o=65535&i,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[n>>8]+x[255&n]}
|
|
29
29
|
/**
|
|
30
30
|
* @license
|
|
31
31
|
* Copyright 2020 Google LLC
|
|
@@ -35,12 +35,12 @@ class b{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
35
35
|
* @license
|
|
36
36
|
* Copyright 2021 Google LLC
|
|
37
37
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
38
|
-
*/const
|
|
38
|
+
*/const _=new WeakMap,$=new Map;function k(t,e,n){if(t){const i=n?.id??function(t){const e="string"==typeof t?t:t.strings;let n=$.get(e);void 0===n&&(n=w(e,"string"!=typeof t&&!("strTag"in t)),$.set(e,n));return n}
|
|
39
39
|
/**
|
|
40
40
|
* @license
|
|
41
41
|
* Copyright 2021 Google LLC
|
|
42
42
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
43
|
-
*/(e),o=t[i];if(o){if("string"==typeof o)return o;if("strTag"in o)return
|
|
43
|
+
*/(e),o=t[i];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(m)throw new Error("lit-localize can only be configured once");g=t,m=!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(n=>{I===e&&(z=t,P=void 0,C=n.templates,S({status:"ready",readyLocale:t}),O.resolve())},n=>{I===e&&(S({status:"error",errorLocale:t,errorMessage:n.toString()}),O.reject(n))}),O.promise};var D=t`
|
|
44
44
|
:host {
|
|
45
45
|
display: block;
|
|
46
46
|
width: 100%;
|
|
@@ -1303,6 +1303,147 @@ class b{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1303
1303
|
pointer-events: none;
|
|
1304
1304
|
}
|
|
1305
1305
|
|
|
1306
|
+
/* ── Audio mic buttons ─────────────────────────────────────────── */
|
|
1307
|
+
.audio-mic-btn {
|
|
1308
|
+
position: relative;
|
|
1309
|
+
display: flex;
|
|
1310
|
+
align-items: center;
|
|
1311
|
+
justify-content: center;
|
|
1312
|
+
width: 32px;
|
|
1313
|
+
height: 32px;
|
|
1314
|
+
border: none;
|
|
1315
|
+
border-radius: 50%;
|
|
1316
|
+
background: transparent;
|
|
1317
|
+
color: var(--chatbot-text-secondary, #8c8ca8);
|
|
1318
|
+
cursor: pointer;
|
|
1319
|
+
transition: background 150ms, color 150ms;
|
|
1320
|
+
flex-shrink: 0;
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
.audio-mic-btn:hover {
|
|
1324
|
+
background: var(--chatbot-input-bg, #f5f5f8);
|
|
1325
|
+
color: var(--chatbot-accent, #7c3aed);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
.audio-mic-btn:disabled {
|
|
1329
|
+
opacity: 0.4;
|
|
1330
|
+
cursor: not-allowed;
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1333
|
+
/* Small badge icon in the bottom-right corner of the mic button */
|
|
1334
|
+
.audio-mic-badge {
|
|
1335
|
+
position: absolute;
|
|
1336
|
+
bottom: 2px;
|
|
1337
|
+
right: 2px;
|
|
1338
|
+
background: var(--chatbot-bg, #fff);
|
|
1339
|
+
border-radius: 3px;
|
|
1340
|
+
pointer-events: none;
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
/* ── Recording bar (replaces input row while active) ───────────── */
|
|
1344
|
+
.audio-recording-bar {
|
|
1345
|
+
display: flex;
|
|
1346
|
+
align-items: center;
|
|
1347
|
+
gap: 10px;
|
|
1348
|
+
padding: 8px 10px;
|
|
1349
|
+
min-height: 52px;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
.audio-rec-cancel {
|
|
1353
|
+
display: flex;
|
|
1354
|
+
align-items: center;
|
|
1355
|
+
justify-content: center;
|
|
1356
|
+
width: 34px;
|
|
1357
|
+
height: 34px;
|
|
1358
|
+
border: none;
|
|
1359
|
+
border-radius: 50%;
|
|
1360
|
+
background: transparent;
|
|
1361
|
+
color: #ef4444;
|
|
1362
|
+
cursor: pointer;
|
|
1363
|
+
flex-shrink: 0;
|
|
1364
|
+
transition: background 150ms;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
.audio-rec-cancel:hover { background: #fef2f2; }
|
|
1368
|
+
|
|
1369
|
+
.audio-rec-indicator {
|
|
1370
|
+
flex: 1;
|
|
1371
|
+
display: flex;
|
|
1372
|
+
align-items: center;
|
|
1373
|
+
gap: 8px;
|
|
1374
|
+
overflow: hidden;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
.audio-rec-dot {
|
|
1378
|
+
width: 10px;
|
|
1379
|
+
height: 10px;
|
|
1380
|
+
border-radius: 50%;
|
|
1381
|
+
background: #ef4444;
|
|
1382
|
+
flex-shrink: 0;
|
|
1383
|
+
animation: audioRecPulse 1s ease-in-out infinite;
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
@keyframes audioRecPulse {
|
|
1387
|
+
0%, 100% { opacity: 1; transform: scale(1); }
|
|
1388
|
+
50% { opacity: 0.5; transform: scale(0.85); }
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
.audio-rec-wave {
|
|
1392
|
+
flex: 1;
|
|
1393
|
+
display: flex;
|
|
1394
|
+
align-items: center;
|
|
1395
|
+
gap: 1.5px;
|
|
1396
|
+
height: 28px;
|
|
1397
|
+
overflow: hidden;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
.audio-rec-bar {
|
|
1401
|
+
width: 3px;
|
|
1402
|
+
min-height: 3px;
|
|
1403
|
+
border-radius: 1.5px;
|
|
1404
|
+
background: #ef4444;
|
|
1405
|
+
opacity: 0.75;
|
|
1406
|
+
transition: height 80ms ease;
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
.audio-rec-time {
|
|
1410
|
+
font-size: 14px;
|
|
1411
|
+
font-weight: 600;
|
|
1412
|
+
font-variant-numeric: tabular-nums;
|
|
1413
|
+
color: var(--chatbot-text, #0f0f3c);
|
|
1414
|
+
flex-shrink: 0;
|
|
1415
|
+
min-width: 38px;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
.audio-rec-mode-label {
|
|
1419
|
+
font-size: 11px;
|
|
1420
|
+
font-weight: 600;
|
|
1421
|
+
color: var(--chatbot-text-secondary, #8c8ca8);
|
|
1422
|
+
white-space: nowrap;
|
|
1423
|
+
flex-shrink: 0;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
.audio-rec-send {
|
|
1427
|
+
display: flex;
|
|
1428
|
+
align-items: center;
|
|
1429
|
+
justify-content: center;
|
|
1430
|
+
width: 34px;
|
|
1431
|
+
height: 34px;
|
|
1432
|
+
border: none;
|
|
1433
|
+
border-radius: 50%;
|
|
1434
|
+
background: var(--chatbot-accent, #7c3aed);
|
|
1435
|
+
color: #fff;
|
|
1436
|
+
cursor: pointer;
|
|
1437
|
+
flex-shrink: 0;
|
|
1438
|
+
transition: background 150ms;
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
.audio-rec-send:hover { background: #6d28d9; }
|
|
1442
|
+
|
|
1443
|
+
/* Transcribe mode: green tint to distinguish from send */
|
|
1444
|
+
.audio-rec-send--transcribe { background: #059669; }
|
|
1445
|
+
.audio-rec-send--transcribe:hover { background: #047857; }
|
|
1446
|
+
|
|
1306
1447
|
/* RTL support */
|
|
1307
1448
|
:host([dir='rtl']) .chat-container--with-threads {
|
|
1308
1449
|
grid-template-columns: 1fr 280px;
|
|
@@ -1680,7 +1821,7 @@ class b{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1680
1821
|
* @license
|
|
1681
1822
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1682
1823
|
* SPDX-License-Identifier: MIT
|
|
1683
|
-
*/;const
|
|
1824
|
+
*/;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,n;super.disconnectedCallback(),null===(t=this.themeObserver)||void 0===t||t.disconnect(),null===(e=this.designSystemObserver)||void 0===e||e.disconnect(),null===(n=this.mediaQuery)||void 0===n||n.removeEventListener("change",this.handleSystemThemeChange)}get currentTheme(){var t,e;const n=(null===(t=this.closest("[data-theme]"))||void 0===t?void 0:t.getAttribute("data-theme"))||document.documentElement.getAttribute("data-theme");return n||((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)},B=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 n of this.requiredComponents)if(!this.isComponentAvailable(n)){e=!1;const i=new Error(`Required component "${n}" is not registered. Please import and register the component before using ${this.tagName.toLowerCase()}.`);t?t(n,i):console.error(i.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)}},L=t=>class extends t{dispatchCustomEvent(t,e){this.dispatchEvent(new CustomEvent(t,{detail:e,bubbles:!0,composed:!0}))}dispatchEventWithMetadata(t,e){var n;const i=Object.assign(Object.assign({},e),{timestamp:Date.now(),componentName:(null===(n=this.tagName)||void 0===n?void 0:n.toLowerCase())||"unknown"});this.dispatchCustomEvent(t,i)}dispatchInputEvent(t,e){const n=Object.assign({target:e.target||this,value:e.value,originalEvent:e.originalEvent},e);this.dispatchCustomEvent(t,n)}dispatchFocusEvent(t,e){const n=Object.assign({target:e.target||this,value:e.value,focused:e.focused,cursorPosition:e.cursorPosition,selectedText:e.selectedText},e);this.dispatchCustomEvent(t,n)}dispatchValidationEvent(t,e){var n;const i=Object.assign({target:e.target||this,value:e.value,isValid:null!==(n=e.isValid)&&void 0!==n&&n,error:e.error},e);this.dispatchCustomEvent(t,i)}dispatchActionEvent(t,e){const n=Object.assign({target:e.target||this,action:e.action,previousValue:e.previousValue,newValue:e.newValue},e);this.dispatchCustomEvent(t,n)}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;
|
|
1684
1825
|
/**
|
|
1685
1826
|
* @license
|
|
1686
1827
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
@@ -1691,23 +1832,23 @@ class b{constructor(){this.settled=!1,this.promise=new Promise((t,e)=>{this._res
|
|
|
1691
1832
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1692
1833
|
* SPDX-License-Identifier: MIT
|
|
1693
1834
|
*/
|
|
1694
|
-
const
|
|
1835
|
+
const H=t=>{class e extends t{constructor(){super(...arguments),this.o=null}createRenderRoot(){return this.constructor.useShadowDom?super.createRenderRoot():this}connectedCallback(){const t=this.constructor.useShadowDom;if(!t&&null===this.o)for(this.o=[];this.firstChild;)this.o.push(this.removeChild(this.firstChild));if(super.connectedCallback(),!t){const t=this.constructor,e=this.tagName.toLowerCase(),n=t.styles;if(n){const t=J(n);t&&function(t,e,n){var i;if(!W.has(t)){const n=new CSSStyleSheet;n.replaceSync(e),W.set(t,n)}const o=W.get(t),s=`doc:${t}`;if(U.has(s)||(document.adoptedStyleSheets=[...document.adoptedStyleSheets,o],U.add(s)),n){let e=n;for(;e;){const n=e.getRootNode();if(!(n instanceof ShadowRoot))break;{const s=`shadow:${((null===(i=n.host)||void 0===i?void 0:i.tagName)||"").toLowerCase()}:${t}`;U.has(s)||(n.adoptedStyleSheets=[...n.adoptedStyleSheets,o],U.add(s)),e=n.host}}}}(e,t,this)}}}get lightChildren(){return this.o?this.o.filter(t=>!(t instanceof Element&&t.hasAttribute("slot"))):[]}lightChildrenNamed(t){return this.o?this.o.filter(e=>e instanceof Element&&e.getAttribute("slot")===t):[]}}return e.useShadowDom=!1,e};function J(t){return Array.isArray(t)?t.map(t=>J(t)).filter(Boolean).join("\n"):t&&"string"==typeof t.cssText?t.cssText:"string"==typeof t?t:""}
|
|
1695
1836
|
/**
|
|
1696
1837
|
* @license
|
|
1697
1838
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1698
1839
|
* SPDX-License-Identifier: MIT
|
|
1699
|
-
*/var
|
|
1840
|
+
*/var q,V,G,K,Y,X,Q;!function(t){t.User="user",t.Bot="bot",t.System="system"}(q||(q={})),function(t){t.Dots="dots",t.Spinner="spinner",t.Wave="wave",t.Typing="typing"}(V||(V={})),function(t){t.Small="small",t.Medium="medium",t.Large="large",t.Full="full"}(G||(G={})),function(t){t.Default="default",t.Minimal="minimal",t.Rounded="rounded",t.ChatGPT="chatgpt"}(K||(K={})),function(t){t.Default="default",t.Error="error",t.Success="success",t.Loading="loading",t.Pending="pending"}(Y||(Y={})),function(t){t.Image="image",t.Document="document",t.Audio="audio",t.Video="video",t.Archive="archive",t.Code="code",t.Unknown="unknown"}(X||(X={})),function(t){t.Upload="upload",t.Clear="clear",t.Export="export",t.Settings="settings",t.Microphone="microphone",t.Camera="camera",t.Attach="attach"}(Q||(Q={}));const Z="",tt=1e3,et=100,nt=10485760,it=5,ot=["image/jpeg","image/png","image/gif","image/webp","application/pdf","text/plain","text/csv","application/json","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],st={"image/":X.Image,"audio/":X.Audio,"video/":X.Video,"application/pdf":X.Document,"application/msword":X.Document,"application/vnd.openxmlformats-officedocument":X.Document,"text/":X.Document,"application/zip":X.Archive,"application/x-rar":X.Archive,"application/javascript":X.Code,"text/html":X.Code,"text/css":X.Code};
|
|
1700
1841
|
/**
|
|
1701
1842
|
* @license
|
|
1702
1843
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1703
1844
|
* SPDX-License-Identifier: MIT
|
|
1704
1845
|
*/
|
|
1705
|
-
function
|
|
1846
|
+
function rt(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.isNaN(e.getTime()))return"";const n=new Date,i={hour:"numeric",minute:"2-digit",hour12:!0};if(e.toDateString()===n.toDateString())return e.toLocaleTimeString(void 0,i);const o=Object.assign({month:"short",day:"numeric"},i);return e.toLocaleDateString(void 0,o)}function at(t){return t.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}const lt={javascript:"JavaScript",typescript:"TypeScript",python:"Python",java:"Java",go:"Go",rust:"Rust",c:"C",cpp:"C++",csharp:"C#",ruby:"Ruby",php:"PHP",swift:"Swift",kotlin:"Kotlin",html:"HTML",css:"CSS",scss:"SCSS",sql:"SQL",graphql:"GraphQL",json:"JSON",yaml:"YAML",xml:"XML",toml:"TOML",markdown:"Markdown",md:"Markdown",bash:"Bash",shell:"Shell",sh:"Shell",zsh:"Zsh",dockerfile:"Dockerfile",makefile:"Makefile",text:"Text"};function ct(t){return lt[t]||t.charAt(0).toUpperCase()+t.slice(1)}function dt(t){let e=at(t);return e=e.replaceAll(/```([\s\S]*?)```/g,'<pre class="md-code"><code>$1</code></pre>'),e=e.replaceAll(/`([^`]+)`/g,'<code class="md-inline-code">$1</code>'),e=e.replaceAll(/^###[^\S\n]+(.+)$/gm,"<h3>$1</h3>"),e=e.replaceAll(/^##[^\S\n]+(.+)$/gm,"<h2>$1</h2>"),e=e.replaceAll(/^#[^\S\n]+(.+)$/gm,"<h1>$1</h1>"),e=e.replaceAll(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),e=e.replaceAll(/\*([^*]+)\*/g,"<em>$1</em>"),e=e.replaceAll(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replaceAll(/(?:^|\n)-\s+(.+)(?=\n|$)/g,(t,e)=>`\n<ul><li>${e}</li></ul>`),e=e.replaceAll(/<ul>\s*<li>([\s\S]*?)<\/li>\s*<\/ul>\n<ul>/g,"<ul><li>$1</li>"),e=e.split(/\n\n+/).map(t=>/^(<h\d|<pre|<ul|<ol|<blockquote)/.test(t.trim())?t:`<p>${t.replaceAll("\n","<br/>")}</p>`).join("\n"),e}
|
|
1706
1847
|
/**
|
|
1707
1848
|
* @license
|
|
1708
1849
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1709
1850
|
* SPDX-License-Identifier: MIT
|
|
1710
|
-
*/function
|
|
1851
|
+
*/function ht(t,i){var o,s,r,c,d,h,u,p;const f=null===(o=t.text)||void 0===o?void 0:o.includes("[ERROR_START]"),m={error:!!t.error||f,introduction:!!t.introduction,[t.sender]:!0};return n`
|
|
1711
1852
|
<div
|
|
1712
1853
|
class="message ${a(m)}"
|
|
1713
1854
|
part="message"
|
|
@@ -1715,15 +1856,15 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1715
1856
|
data-id="${t.id}"
|
|
1716
1857
|
>
|
|
1717
1858
|
<div class="message__content" part="message-content">
|
|
1718
|
-
${
|
|
1859
|
+
${f?function(t){const e=t.match(/\[ERROR_START\]\[ERROR_TITLE_START\]([\s\S]*?)\[ERROR_TITLE_END\]([\s\S]*?)\[ERROR_END\]/);if(e){const t=e[1],i=e[2];return n`
|
|
1719
1860
|
<div class="message__error-container" part="message-error">
|
|
1720
1861
|
${t?n`<div class="message__error-title" part="message-error-title">${t}</div>`:""}
|
|
1721
1862
|
<div class="message__error-description" part="message-error-description">${i}</div>
|
|
1722
1863
|
</div>
|
|
1723
|
-
`}return n`${t}`}(null!==(r=null===(s=t.text)||void 0===s?void 0:s.trim())&&void 0!==r?r:""):(null===(
|
|
1864
|
+
`}return n`${t}`}(null!==(r=null===(s=t.text)||void 0===s?void 0:s.trim())&&void 0!==r?r:""):(null===(c=null==t?void 0:t.metadata)||void 0===c?void 0:c.renderAsHtml)?l(null!==(h=null===(d=t.text)||void 0===d?void 0:d.trim())&&void 0!==h?h:""):l((null!==(p=null===(u=t.text)||void 0===u?void 0:u.trim())&&void 0!==p?p:"").replaceAll("\n","<br>"))}
|
|
1724
1865
|
</div>
|
|
1725
1866
|
${t.files&&t.files.length>0?n`
|
|
1726
|
-
<div class="message__attachments" part="message-attachments" role="list" aria-label="${
|
|
1867
|
+
<div class="message__attachments" part="message-attachments" role="list" aria-label="${g("Attached files")}">
|
|
1727
1868
|
${t.files.map(t=>{return n`
|
|
1728
1869
|
<nr-dropdown
|
|
1729
1870
|
trigger="hover"
|
|
@@ -1766,7 +1907,7 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1766
1907
|
`:e}
|
|
1767
1908
|
<div class="message__footer" part="message-footer">
|
|
1768
1909
|
<div class="message__timestamp" part="message-timestamp">
|
|
1769
|
-
${
|
|
1910
|
+
${rt(t.timestamp)}
|
|
1770
1911
|
</div>
|
|
1771
1912
|
<nr-icon
|
|
1772
1913
|
name="copy"
|
|
@@ -1775,8 +1916,8 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1775
1916
|
class="message__copy"
|
|
1776
1917
|
@click=${()=>i.onCopy(t)}
|
|
1777
1918
|
@keydown=${e=>i.onCopyKeydown(e,t)}
|
|
1778
|
-
title="${
|
|
1779
|
-
aria-label="${
|
|
1919
|
+
title="${g("Copy message")}"
|
|
1920
|
+
aria-label="${g("Copy message")}"
|
|
1780
1921
|
role="button"
|
|
1781
1922
|
tabindex="0"
|
|
1782
1923
|
></nr-icon>
|
|
@@ -1789,23 +1930,23 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1789
1930
|
part="retry-button"
|
|
1790
1931
|
@click=${()=>i.onRetry(t)}
|
|
1791
1932
|
@keydown=${i.onRetryKeydown}
|
|
1792
|
-
aria-label="${
|
|
1933
|
+
aria-label="${g("Retry message")}"
|
|
1793
1934
|
>
|
|
1794
|
-
${
|
|
1935
|
+
${g("Retry")}
|
|
1795
1936
|
</nr-button>`:e}
|
|
1796
1937
|
</div>
|
|
1797
|
-
`}function
|
|
1938
|
+
`}function ut(t,i,o,s){return n`
|
|
1798
1939
|
<div class="messages" part="messages">
|
|
1799
1940
|
${0===t.length?n`
|
|
1800
1941
|
<div class="empty-state" part="empty-state">
|
|
1801
1942
|
<slot name="empty-state">
|
|
1802
1943
|
<div class="empty-state__content">
|
|
1803
|
-
${
|
|
1944
|
+
${g("Start a conversation")}
|
|
1804
1945
|
</div>
|
|
1805
1946
|
</slot>
|
|
1806
1947
|
</div>
|
|
1807
1948
|
`:e}
|
|
1808
|
-
${t.map(t=>
|
|
1949
|
+
${t.map(t=>ht(t,s))}
|
|
1809
1950
|
${i}
|
|
1810
1951
|
${o}
|
|
1811
1952
|
</div>
|
|
@@ -1814,7 +1955,7 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1814
1955
|
* @license
|
|
1815
1956
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1816
1957
|
* SPDX-License-Identifier: MIT
|
|
1817
|
-
*/function
|
|
1958
|
+
*/function pt(t,i,o){return i.length>0?n`
|
|
1818
1959
|
<div class="suggestion-container" part="suggestions">
|
|
1819
1960
|
${i.map(t=>function(t,e){return n`
|
|
1820
1961
|
<div
|
|
@@ -1825,7 +1966,7 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1825
1966
|
@click=${()=>e.onClick(t)}
|
|
1826
1967
|
@keydown=${e.onKeydown}
|
|
1827
1968
|
data-id="${t.id}"
|
|
1828
|
-
aria-label="${
|
|
1969
|
+
aria-label="${g("Select suggestion: ")}${t.text}"
|
|
1829
1970
|
>
|
|
1830
1971
|
${t.text}
|
|
1831
1972
|
</div>
|
|
@@ -1836,9 +1977,9 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1836
1977
|
* @license
|
|
1837
1978
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1838
1979
|
* SPDX-License-Identifier: MIT
|
|
1839
|
-
*/function
|
|
1980
|
+
*/function ft(t,e,i){return n`
|
|
1840
1981
|
<div class="context-tags-row" part="context-tags">
|
|
1841
|
-
${
|
|
1982
|
+
${c(t,t=>t.id,t=>{return n`
|
|
1842
1983
|
<nr-dropdown
|
|
1843
1984
|
trigger="hover"
|
|
1844
1985
|
placement="top"
|
|
@@ -1879,7 +2020,7 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1879
2020
|
</nr-dropdown>
|
|
1880
2021
|
`;var o})}
|
|
1881
2022
|
</div>
|
|
1882
|
-
`}function
|
|
2023
|
+
`}function gt(t,i){return n`
|
|
1883
2024
|
<div class="action-buttons-row">
|
|
1884
2025
|
<div class="action-buttons-left">
|
|
1885
2026
|
${t.enableFileUpload?function(t,e){return n`
|
|
@@ -1899,8 +2040,8 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1899
2040
|
size="small"
|
|
1900
2041
|
.icon=${["upload"]}
|
|
1901
2042
|
?disabled=${t.disabled}
|
|
1902
|
-
aria-label="${
|
|
1903
|
-
title="${
|
|
2043
|
+
aria-label="${g("Attach files")}"
|
|
2044
|
+
title="${g("Attach files")}"
|
|
1904
2045
|
>
|
|
1905
2046
|
Attach
|
|
1906
2047
|
</nr-button>
|
|
@@ -1915,12 +2056,12 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1915
2056
|
size="small"
|
|
1916
2057
|
?disabled=${t.disabled}
|
|
1917
2058
|
searchable
|
|
1918
|
-
search-placeholder="${
|
|
2059
|
+
search-placeholder="${g("Search modules...")}"
|
|
1919
2060
|
use-custom-selected-display
|
|
1920
2061
|
part="module-select"
|
|
1921
2062
|
class="module-select"
|
|
1922
2063
|
@nr-change=${e.onModuleChange}
|
|
1923
|
-
aria-label="${
|
|
2064
|
+
aria-label="${g("Select modules")}"
|
|
1924
2065
|
>
|
|
1925
2066
|
<span slot="selected-display">
|
|
1926
2067
|
${t.renderModuleDisplay()}
|
|
@@ -1928,8 +2069,45 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1928
2069
|
</nr-select>
|
|
1929
2070
|
`}(t,i):e}
|
|
1930
2071
|
</div>
|
|
1931
|
-
|
|
2072
|
+
|
|
1932
2073
|
<div class="action-buttons-right">
|
|
2074
|
+
${t.showAudioButton&&!t.isQueryRunning?n`
|
|
2075
|
+
<!-- Speech-to-text: mic + keyboard indicator -->
|
|
2076
|
+
<button
|
|
2077
|
+
class="audio-mic-btn"
|
|
2078
|
+
title="${g("Record speech to text")}"
|
|
2079
|
+
?disabled=${t.disabled}
|
|
2080
|
+
@click=${()=>{var t;return null===(t=i.onAudioStart)||void 0===t?void 0:t.call(i,"transcribe")}}
|
|
2081
|
+
aria-label="${g("Record speech to text")}"
|
|
2082
|
+
>
|
|
2083
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2084
|
+
<path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/>
|
|
2085
|
+
<path d="M19 10v2a7 7 0 01-14 0v-2"/>
|
|
2086
|
+
<line x1="12" y1="19" x2="12" y2="23"/>
|
|
2087
|
+
</svg>
|
|
2088
|
+
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="audio-mic-badge">
|
|
2089
|
+
<rect x="2" y="7" width="20" height="14" rx="2"/>
|
|
2090
|
+
<path d="M7 12h2l2 3 2-5 2 2h2"/>
|
|
2091
|
+
</svg>
|
|
2092
|
+
</button>
|
|
2093
|
+
<!-- Voice message: mic + waveform indicator -->
|
|
2094
|
+
<button
|
|
2095
|
+
class="audio-mic-btn"
|
|
2096
|
+
title="${g("Send voice message")}"
|
|
2097
|
+
?disabled=${t.disabled}
|
|
2098
|
+
@click=${()=>{var t;return null===(t=i.onAudioStart)||void 0===t?void 0:t.call(i,"message")}}
|
|
2099
|
+
aria-label="${g("Send voice message")}"
|
|
2100
|
+
>
|
|
2101
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2102
|
+
<path d="M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z"/>
|
|
2103
|
+
<path d="M19 10v2a7 7 0 01-14 0v-2"/>
|
|
2104
|
+
<line x1="12" y1="19" x2="12" y2="23"/>
|
|
2105
|
+
</svg>
|
|
2106
|
+
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="audio-mic-badge">
|
|
2107
|
+
<path d="M2 12h2M6 8h2M10 6h2M14 8h2M18 12h2M22 12h2"/>
|
|
2108
|
+
</svg>
|
|
2109
|
+
</button>
|
|
2110
|
+
`:e}
|
|
1933
2111
|
${t.showSendButton&&(!t.disabled||t.isQueryRunning)&&(t.currentInput.trim()||t.uploadedFiles.length>0||t.isQueryRunning)?function(t,e){return n`
|
|
1934
2112
|
<nr-button
|
|
1935
2113
|
class="input-box__send-button"
|
|
@@ -1939,21 +2117,96 @@ function st(t){if(!t)return"";const e=t instanceof Date?t:new Date(t);if(Number.
|
|
|
1939
2117
|
.iconRight=${t.isQueryRunning?"square":"arrow-up"}
|
|
1940
2118
|
@click=${t.isQueryRunning?e.onStop:e.onSend}
|
|
1941
2119
|
@keydown=${e.onSendKeydown}
|
|
1942
|
-
aria-label="${t.isQueryRunning?
|
|
1943
|
-
title="${t.isQueryRunning?
|
|
2120
|
+
aria-label="${t.isQueryRunning?g("Stop query"):g("Send message")}"
|
|
2121
|
+
title="${t.isQueryRunning?g("Stop query"):g("Send message")}"
|
|
1944
2122
|
>
|
|
1945
|
-
${t.isQueryRunning?
|
|
2123
|
+
${t.isQueryRunning?g("Stop"):g("Send")}
|
|
1946
2124
|
</nr-button>
|
|
1947
2125
|
`}(t,i):e}
|
|
1948
2126
|
</div>
|
|
1949
2127
|
</div>
|
|
2128
|
+
`}function mt(t,i){return t.audioRecording.active?n`
|
|
2129
|
+
<div class="input-box" part="input-box">
|
|
2130
|
+
<div class="input-container" part="input-container">
|
|
2131
|
+
${function(t,e){const{duration:i,bars:o}=t.audioRecording,s="transcribe"===t.audioMode,r=g(s?"Convert to text":"Send as voice message"),a=s?n`<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2132
|
+
<rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>
|
|
2133
|
+
<path d="M7 10h2l2 3 2-6 2 3h2"/>
|
|
2134
|
+
</svg>`:n`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
|
|
2135
|
+
<path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>
|
|
2136
|
+
</svg>`;return n`
|
|
2137
|
+
<div class="audio-recording-bar">
|
|
2138
|
+
<button
|
|
2139
|
+
class="audio-rec-cancel"
|
|
2140
|
+
title="${g("Cancel recording")}"
|
|
2141
|
+
@click=${e.onAudioCancel}
|
|
2142
|
+
aria-label="${g("Cancel recording")}"
|
|
2143
|
+
>
|
|
2144
|
+
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
2145
|
+
<polyline points="3 6 5 6 21 6"/>
|
|
2146
|
+
<path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/>
|
|
2147
|
+
<path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/>
|
|
2148
|
+
</svg>
|
|
2149
|
+
</button>
|
|
2150
|
+
|
|
2151
|
+
<div class="audio-rec-indicator">
|
|
2152
|
+
<span class="audio-rec-dot"></span>
|
|
2153
|
+
<div class="audio-rec-wave">
|
|
2154
|
+
${o.map(t=>n`
|
|
2155
|
+
<div class="audio-rec-bar" style=${d({height:`${Math.round(24*t)}px`})}></div>
|
|
2156
|
+
`)}
|
|
2157
|
+
</div>
|
|
2158
|
+
<span class="audio-rec-time">${i}</span>
|
|
2159
|
+
</div>
|
|
2160
|
+
|
|
2161
|
+
<span class="audio-rec-mode-label">
|
|
2162
|
+
${g(s?"Speech to text":"Voice message")}
|
|
2163
|
+
</span>
|
|
2164
|
+
|
|
2165
|
+
<button
|
|
2166
|
+
class="audio-rec-send ${s?"audio-rec-send--transcribe":""}"
|
|
2167
|
+
title="${r}"
|
|
2168
|
+
@click=${e.onAudioSend}
|
|
2169
|
+
aria-label="${r}"
|
|
2170
|
+
>
|
|
2171
|
+
${a}
|
|
2172
|
+
</button>
|
|
2173
|
+
</div>
|
|
2174
|
+
`}(t,i)}
|
|
2175
|
+
</div>
|
|
2176
|
+
</div>
|
|
2177
|
+
`:n`
|
|
2178
|
+
<div class="input-box" part="input-box">
|
|
2179
|
+
<div class="input-container" part="input-container">
|
|
2180
|
+
<!-- Context tags -->
|
|
2181
|
+
${t.uploadedFiles.length>0?ft(t.uploadedFiles,i.onFileRemove,i.onFileClick):e}
|
|
2182
|
+
|
|
2183
|
+
<!-- Input area -->
|
|
2184
|
+
<div class="input-row">
|
|
2185
|
+
<div
|
|
2186
|
+
class="input-box__input"
|
|
2187
|
+
part="input"
|
|
2188
|
+
contenteditable="true"
|
|
2189
|
+
role="textbox"
|
|
2190
|
+
aria-multiline="true"
|
|
2191
|
+
aria-label="${g("Chat input")}"
|
|
2192
|
+
data-placeholder="${t.placeholder}"
|
|
2193
|
+
@input=${i.onInput}
|
|
2194
|
+
@keydown=${i.onKeydown}
|
|
2195
|
+
@focus=${i.onFocus}
|
|
2196
|
+
@blur=${i.onBlur}
|
|
2197
|
+
></div>
|
|
2198
|
+
</div>
|
|
2199
|
+
|
|
2200
|
+
<!-- Action buttons -->
|
|
2201
|
+
${gt(t,i)}
|
|
2202
|
+
</div>
|
|
2203
|
+
</div>
|
|
1950
2204
|
`}
|
|
1951
2205
|
/**
|
|
1952
2206
|
* @license
|
|
1953
2207
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
1954
2208
|
* SPDX-License-Identifier: MIT
|
|
1955
|
-
*/
|
|
1956
|
-
function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:null,s=o&&"string"==typeof o.text?o.text:"";return n`
|
|
2209
|
+
*/function vt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:null,s=o&&"string"==typeof o.text?o.text:"";return n`
|
|
1957
2210
|
<div
|
|
1958
2211
|
class="thread-item ${a({"thread-item--active":t.id===e.activeThreadId})}"
|
|
1959
2212
|
@click=${()=>i.onSelectThread(t.id)}
|
|
@@ -1970,13 +2223,13 @@ function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:n
|
|
|
1970
2223
|
@blur=${e=>{const n=e.target.value.trim();n&&n!==t.title?i.onRenameThread(t.id,n):i.onRenameThread(t.id,t.title||"")}}
|
|
1971
2224
|
/>
|
|
1972
2225
|
`:n`
|
|
1973
|
-
<div class="thread-item__title">${t.title||
|
|
2226
|
+
<div class="thread-item__title">${t.title||g("New Chat")}</div>
|
|
1974
2227
|
`}
|
|
1975
2228
|
<div class="thread-item__actions">
|
|
1976
2229
|
${i.onRenameThread&&e.editingThreadId!==t.id?n`
|
|
1977
2230
|
<button
|
|
1978
2231
|
class="thread-item__action-btn"
|
|
1979
|
-
title="${
|
|
2232
|
+
title="${g("Rename conversation")}"
|
|
1980
2233
|
@click=${e=>{e.stopPropagation(),e.target.dispatchEvent(new CustomEvent("nr-thread-edit",{bubbles:!0,composed:!0,detail:{threadId:t.id}}))}}
|
|
1981
2234
|
part="thread-rename"
|
|
1982
2235
|
>
|
|
@@ -1986,7 +2239,7 @@ function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:n
|
|
|
1986
2239
|
${i.onBookmarkThread?n`
|
|
1987
2240
|
<button
|
|
1988
2241
|
class="thread-item__action-btn ${t.bookmarked?"thread-item__bookmark--active":""}"
|
|
1989
|
-
title="${t.bookmarked?
|
|
2242
|
+
title="${t.bookmarked?g("Remove bookmark"):g("Bookmark conversation")}"
|
|
1990
2243
|
@click=${e=>{e.stopPropagation(),i.onBookmarkThread(t.id)}}
|
|
1991
2244
|
part="thread-bookmark"
|
|
1992
2245
|
>
|
|
@@ -1999,10 +2252,10 @@ function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:n
|
|
|
1999
2252
|
`:""}
|
|
2000
2253
|
${i.onDeleteThread?n`
|
|
2001
2254
|
<nr-popconfirm
|
|
2002
|
-
title="${
|
|
2003
|
-
description="${
|
|
2004
|
-
ok-text="${
|
|
2005
|
-
cancel-text="${
|
|
2255
|
+
title="${g("Delete this conversation?")}"
|
|
2256
|
+
description="${g("This action cannot be undone.")}"
|
|
2257
|
+
ok-text="${g("Delete")}"
|
|
2258
|
+
cancel-text="${g("Cancel")}"
|
|
2006
2259
|
ok-type="danger"
|
|
2007
2260
|
placement="right"
|
|
2008
2261
|
@click=${t=>t.stopPropagation()}
|
|
@@ -2011,7 +2264,7 @@ function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:n
|
|
|
2011
2264
|
<button
|
|
2012
2265
|
slot="trigger"
|
|
2013
2266
|
class="thread-item__action-btn thread-item__delete"
|
|
2014
|
-
title="${
|
|
2267
|
+
title="${g("Delete conversation")}"
|
|
2015
2268
|
part="thread-delete"
|
|
2016
2269
|
>
|
|
2017
2270
|
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>
|
|
@@ -2023,9 +2276,9 @@ function gt(t,e,i){const o=t.messages.length>0?t.messages[t.messages.length-1]:n
|
|
|
2023
2276
|
<div class="thread-item__preview">
|
|
2024
2277
|
${s}
|
|
2025
2278
|
</div>
|
|
2026
|
-
<div class="thread-item__timestamp">${
|
|
2279
|
+
<div class="thread-item__timestamp">${rt(t.updatedAt)}</div>
|
|
2027
2280
|
</div>
|
|
2028
|
-
`}function
|
|
2281
|
+
`}function bt(t,i){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 n`
|
|
2029
2282
|
<nr-modal
|
|
2030
2283
|
.open=${t.isOpen}
|
|
2031
2284
|
size="large"
|
|
@@ -2080,7 +2333,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2080
2333
|
* @license
|
|
2081
2334
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2082
2335
|
* SPDX-License-Identifier: MIT
|
|
2083
|
-
*/function
|
|
2336
|
+
*/function yt(t,i){var o;if(!t.isOpen||!t.artifact)return e;const s=t.artifact,r=ct(s.language);return n`
|
|
2084
2337
|
<div class="artifact-panel" part="artifact-panel">
|
|
2085
2338
|
<div class="artifact-panel__resize-handle" part="artifact-panel-resize-handle">
|
|
2086
2339
|
<div class="artifact-panel__resize-bar"></div>
|
|
@@ -2097,16 +2350,16 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2097
2350
|
size="small"
|
|
2098
2351
|
.icon=${["copy"]}
|
|
2099
2352
|
@click=${()=>i.onCopy(s)}
|
|
2100
|
-
title="${
|
|
2101
|
-
aria-label="${
|
|
2353
|
+
title="${g("Copy code")}"
|
|
2354
|
+
aria-label="${g("Copy code")}"
|
|
2102
2355
|
></nr-button>
|
|
2103
2356
|
<nr-button
|
|
2104
2357
|
type="text"
|
|
2105
2358
|
size="small"
|
|
2106
2359
|
.icon=${["x"]}
|
|
2107
2360
|
@click=${i.onClose}
|
|
2108
|
-
title="${
|
|
2109
|
-
aria-label="${
|
|
2361
|
+
title="${g("Close panel")}"
|
|
2362
|
+
aria-label="${g("Close panel")}"
|
|
2110
2363
|
></nr-button>
|
|
2111
2364
|
</div>
|
|
2112
2365
|
</div>
|
|
@@ -2120,9 +2373,9 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2120
2373
|
* @license
|
|
2121
2374
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2122
2375
|
* SPDX-License-Identifier: MIT
|
|
2123
|
-
*/function
|
|
2376
|
+
*/function xt(t,i){return!1!==t.showMessages?n`
|
|
2124
2377
|
<div class="chatbot-content" part="content">
|
|
2125
|
-
${
|
|
2378
|
+
${ut(t.messages,pt(t.chatStarted,t.suggestions,i.suggestion),t.isTyping?function(t,i,o){if(!t)return e;const s=i===V.Dots?n`
|
|
2126
2379
|
<div class="dots">
|
|
2127
2380
|
<span></span>
|
|
2128
2381
|
<span></span>
|
|
@@ -2135,20 +2388,20 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2135
2388
|
${o?n`<span class="loading-text">${o.split("").map((t,e)=>n`<span class="loading-text__char" style="animation-delay:${.04*e}s">${" "===t?" ":t}</span>`)}</span>`:e}
|
|
2136
2389
|
</div>
|
|
2137
2390
|
</div>
|
|
2138
|
-
`}(t.isTyping,t.loadingIndicator||
|
|
2391
|
+
`}(t.isTyping,t.loadingIndicator||V.Spinner,t.loadingText):e,i.message)}
|
|
2139
2392
|
<slot name="messages"></slot>
|
|
2140
2393
|
</div>
|
|
2141
2394
|
`:t.suggestions&&t.suggestions.length>0?n`
|
|
2142
2395
|
<div class="input-only-suggestions" part="input-only-suggestions">
|
|
2143
|
-
${
|
|
2396
|
+
${pt(0,t.suggestions,i.suggestion)}
|
|
2144
2397
|
</div>
|
|
2145
|
-
`:e}function
|
|
2398
|
+
`:e}function wt(t,i){var o;const s=t.enableArtifacts&&(null===(o=t.artifactPanel)||void 0===o?void 0:o.isOpen);return n`
|
|
2146
2399
|
<div class="chatbot-container ${a({"chatbot-container--with-sidebar":t.enableThreads&&t.isThreadSidebarOpen,"chatbot-container--with-artifact-panel":!!s})}" part="container">
|
|
2147
2400
|
|
|
2148
2401
|
${t.enableThreads&&t.isThreadSidebarOpen&&t.threadSidebar&&i.threadSidebar?function(t,i){const o=t.threads.filter(t=>t.bookmarked),s=t.threads.filter(t=>!t.bookmarked);return n`
|
|
2149
2402
|
<div class="thread-sidebar" part="thread-sidebar">
|
|
2150
2403
|
<div class="thread-sidebar__header">
|
|
2151
|
-
<h3>${
|
|
2404
|
+
<h3>${g("Conversations")}</h3>
|
|
2152
2405
|
</div>
|
|
2153
2406
|
|
|
2154
2407
|
<div class="thread-list">
|
|
@@ -2156,18 +2409,18 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2156
2409
|
<div class="thread-section" part="thread-section-bookmarks">
|
|
2157
2410
|
<div class="thread-section__label">
|
|
2158
2411
|
<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>
|
|
2159
|
-
${
|
|
2412
|
+
${g("Bookmarks")}
|
|
2160
2413
|
</div>
|
|
2161
|
-
${
|
|
2414
|
+
${c(o,t=>t.id,e=>vt(e,t,i))}
|
|
2162
2415
|
</div>
|
|
2163
2416
|
`:e}
|
|
2164
2417
|
${s.length>0||0===o.length?n`
|
|
2165
2418
|
${o.length>0?n`
|
|
2166
|
-
<div class="thread-section__label">${
|
|
2419
|
+
<div class="thread-section__label">${g("All Conversations")}</div>
|
|
2167
2420
|
`:e}
|
|
2168
|
-
${
|
|
2421
|
+
${c(s,t=>t.id,e=>vt(e,t,i))}
|
|
2169
2422
|
${0===s.length&&0===o.length?n`
|
|
2170
|
-
<p class="empty-msg">${
|
|
2423
|
+
<p class="empty-msg">${g("No conversations yet")}</p>
|
|
2171
2424
|
`:e}
|
|
2172
2425
|
`:e}
|
|
2173
2426
|
</div>
|
|
@@ -2189,8 +2442,8 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2189
2442
|
size="small"
|
|
2190
2443
|
.icon=${["panel-left"]}
|
|
2191
2444
|
@click=${i.onToggleThreadSidebar}
|
|
2192
|
-
title="${
|
|
2193
|
-
aria-label="${
|
|
2445
|
+
title="${g(t.isThreadSidebarOpen?"Hide threads":"Show threads")}"
|
|
2446
|
+
aria-label="${g(t.isThreadSidebarOpen?"Hide threads":"Show threads")}"
|
|
2194
2447
|
></nr-button>
|
|
2195
2448
|
${t.enableThreadCreation&&t.messages.length>0?n`
|
|
2196
2449
|
<nr-button
|
|
@@ -2198,8 +2451,8 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2198
2451
|
size="small"
|
|
2199
2452
|
.icon=${["square-pen"]}
|
|
2200
2453
|
@click=${null===(o=i.threadSidebar)||void 0===o?void 0:o.onCreateNew}
|
|
2201
|
-
title="${
|
|
2202
|
-
aria-label="${
|
|
2454
|
+
title="${g("New conversation")}"
|
|
2455
|
+
aria-label="${g("New conversation")}"
|
|
2203
2456
|
></nr-button>
|
|
2204
2457
|
`:""}
|
|
2205
2458
|
</div>
|
|
@@ -2207,41 +2460,14 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2207
2460
|
|
|
2208
2461
|
<slot name="header"></slot>
|
|
2209
2462
|
|
|
2210
|
-
${
|
|
2463
|
+
${xt(t,i)}
|
|
2211
2464
|
|
|
2212
|
-
${
|
|
2213
|
-
<div class="input-box" part="input-box">
|
|
2214
|
-
<div class="input-container">
|
|
2215
|
-
<!-- Context tags -->
|
|
2216
|
-
${t.uploadedFiles.length>0?pt(t.uploadedFiles,i.onFileRemove,i.onFileClick):e}
|
|
2217
|
-
|
|
2218
|
-
<!-- Input area -->
|
|
2219
|
-
<div class="input-row">
|
|
2220
|
-
<div
|
|
2221
|
-
class="input-box__input"
|
|
2222
|
-
part="input"
|
|
2223
|
-
contenteditable="true"
|
|
2224
|
-
role="textbox"
|
|
2225
|
-
aria-multiline="true"
|
|
2226
|
-
aria-label="${f("Chat input")}"
|
|
2227
|
-
data-placeholder="${t.placeholder}"
|
|
2228
|
-
@input=${i.onInput}
|
|
2229
|
-
@keydown=${i.onKeydown}
|
|
2230
|
-
@focus=${i.onFocus}
|
|
2231
|
-
@blur=${i.onBlur}
|
|
2232
|
-
></div>
|
|
2233
|
-
</div>
|
|
2234
|
-
|
|
2235
|
-
<!-- Action buttons -->
|
|
2236
|
-
${ft(t,i)}
|
|
2237
|
-
</div>
|
|
2238
|
-
</div>
|
|
2239
|
-
`}(t.inputBox,i.inputBox)}
|
|
2465
|
+
${mt(t.inputBox,i.inputBox)}
|
|
2240
2466
|
|
|
2241
2467
|
<slot name="footer"></slot>
|
|
2242
2468
|
</div>
|
|
2243
2469
|
|
|
2244
|
-
${s&&t.artifactPanel&&i.artifactPanel?
|
|
2470
|
+
${s&&t.artifactPanel&&i.artifactPanel?yt(t.artifactPanel,i.artifactPanel):""}
|
|
2245
2471
|
|
|
2246
2472
|
${t.isDragging?function(t,e){return n`
|
|
2247
2473
|
<div
|
|
@@ -2254,7 +2480,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2254
2480
|
<div class="file-upload-area__content">
|
|
2255
2481
|
<div class="file-upload-area__icon">📁</div>
|
|
2256
2482
|
<div class="file-upload-area__text">
|
|
2257
|
-
${
|
|
2483
|
+
${g("Drop files here to upload")}
|
|
2258
2484
|
</div>
|
|
2259
2485
|
</div>
|
|
2260
2486
|
</div>
|
|
@@ -2271,7 +2497,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2271
2497
|
@nr-modal-close=${i.onClose}
|
|
2272
2498
|
part="url-modal"
|
|
2273
2499
|
>
|
|
2274
|
-
<div slot="header">${
|
|
2500
|
+
<div slot="header">${g("Add URL")}</div>
|
|
2275
2501
|
|
|
2276
2502
|
<div >
|
|
2277
2503
|
<nr-row gutter="8" align="bottom">
|
|
@@ -2280,12 +2506,12 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2280
2506
|
|
|
2281
2507
|
type="url"
|
|
2282
2508
|
.value=${t.urlInput}
|
|
2283
|
-
placeholder="${
|
|
2509
|
+
placeholder="${g("Enter URL...")}"
|
|
2284
2510
|
?disabled=${t.isLoading}
|
|
2285
2511
|
@nr-input=${i.onUrlInputChange}
|
|
2286
2512
|
@keydown=${i.onUrlInputKeydown}
|
|
2287
2513
|
>
|
|
2288
|
-
<nr-label slot="label">${
|
|
2514
|
+
<nr-label slot="label">${g("URL")}</nr-label>
|
|
2289
2515
|
</nr-input>
|
|
2290
2516
|
</nr-col>
|
|
2291
2517
|
<nr-col span="4" >
|
|
@@ -2295,7 +2521,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2295
2521
|
size="small"
|
|
2296
2522
|
?disabled=${t.isLoading}
|
|
2297
2523
|
@click=${i.onAttachFile}
|
|
2298
|
-
title="${
|
|
2524
|
+
title="${g("Load file from URL")}"
|
|
2299
2525
|
style="margin-left: 0.5rem;"
|
|
2300
2526
|
>
|
|
2301
2527
|
</nr-button>
|
|
@@ -2317,7 +2543,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2317
2543
|
type="success"
|
|
2318
2544
|
style="margin-top: 1rem;"
|
|
2319
2545
|
>
|
|
2320
|
-
${
|
|
2546
|
+
${g("Selected file")}: ${t.selectedFileName}
|
|
2321
2547
|
</nr-alert>
|
|
2322
2548
|
`:e}
|
|
2323
2549
|
|
|
@@ -2326,7 +2552,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2326
2552
|
type="info"
|
|
2327
2553
|
style="margin-top: 1rem;"
|
|
2328
2554
|
>
|
|
2329
|
-
${
|
|
2555
|
+
${g("Loading file from URL...")}
|
|
2330
2556
|
</nr-alert>
|
|
2331
2557
|
`:e}
|
|
2332
2558
|
</div>
|
|
@@ -2338,7 +2564,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2338
2564
|
?disabled=${t.isLoading}
|
|
2339
2565
|
@click=${i.onClose}
|
|
2340
2566
|
>
|
|
2341
|
-
${
|
|
2567
|
+
${g("Cancel")}
|
|
2342
2568
|
</nr-button>
|
|
2343
2569
|
<nr-button
|
|
2344
2570
|
type="primary"
|
|
@@ -2347,7 +2573,7 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2347
2573
|
?loading=${t.isLoading}
|
|
2348
2574
|
@click=${i.onConfirm}
|
|
2349
2575
|
>
|
|
2350
|
-
${
|
|
2576
|
+
${g("Add")}
|
|
2351
2577
|
</nr-button>
|
|
2352
2578
|
</div>
|
|
2353
2579
|
</nr-modal>
|
|
@@ -2356,11 +2582,16 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2356
2582
|
<slot></slot>
|
|
2357
2583
|
</div>
|
|
2358
2584
|
`}
|
|
2585
|
+
/**
|
|
2586
|
+
* @license
|
|
2587
|
+
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2588
|
+
* SPDX-License-Identifier: MIT
|
|
2589
|
+
*/var _t=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};const $t={active:!1,duration:"00:00",bars:[]};class kt{constructor(t){this.state=Object.assign({},$t),this._mediaRecorder=null,this._audioChunks=[],this._waveformSamples=[],this._analyser=null,this._timer=null,this._animFrame=0,this._startTime=0,this._stopResolve=null,this.host=t,t.addController(this)}hostConnected(){}hostDisconnected(){this.cancel()}start(){return _t(this,void 0,void 0,function*(){try{const t=yield navigator.mediaDevices.getUserMedia({audio:!0});this._audioChunks=[],this._waveformSamples=[];const e=["audio/webm;codecs=opus","audio/webm","audio/mp4","audio/aac",""].find(t=>!t||MediaRecorder.isTypeSupported(t))||"";this._mediaRecorder=new MediaRecorder(t,e?{mimeType:e}:void 0);const n=new AudioContext;"suspended"===n.state&&(yield n.resume());const i=n.createMediaStreamSource(t);this._analyser=n.createAnalyser(),this._analyser.fftSize=256,this._analyser.smoothingTimeConstant=.3,i.connect(this._analyser),this._mediaRecorder.ondataavailable=t=>{t.data.size>0&&this._audioChunks.push(t.data)},this._mediaRecorder.onstop=()=>{var e;t.getTracks().forEach(t=>t.stop()),n.close().catch(()=>{}),this._timer&&clearInterval(this._timer),cancelAnimationFrame(this._animFrame),this._analyser=null,null===(e=this._stopResolve)||void 0===e||e.call(this,[...this._audioChunks]),this._stopResolve=null},this._mediaRecorder.start(100),this._startTime=Date.now(),this.state={active:!0,duration:"00:00",bars:[]},this.host.requestUpdate(),this._timer=setInterval(()=>{const t=Math.floor((Date.now()-this._startTime)/1e3),e=Math.floor(t/60).toString().padStart(2,"0"),n=(t%60).toString().padStart(2,"0");this.state=Object.assign(Object.assign({},this.state),{duration:`${e}:${n}`}),this.host.requestUpdate()},500);let o=0;const s=()=>{if(!this._analyser||!this.state.active)return;const t=performance.now();if(t-o>80){o=t;const e=this._analyser.frequencyBinCount,n=new Uint8Array(e);this._analyser.getByteFrequencyData(n);let i=n.reduce((t,e)=>t+e,0)/e;if(i<1){this._analyser.getByteTimeDomainData(n);let t=0;for(let i=0;i<e;i++){const e=Math.abs(n[i]-128);e>t&&(t=e)}i=t}const s=Math.min(1,i/128);this._waveformSamples.push(s);const r=this._waveformSamples.slice(-40).map(t=>Math.max(.08,t));this.state=Object.assign(Object.assign({},this.state),{bars:r}),this.host.requestUpdate()}this._animFrame=requestAnimationFrame(s)};this._animFrame=requestAnimationFrame(s)}catch(t){console.error("[ChatbotAudio] Mic access denied")}})}cancel(){var t;"recording"===(null===(t=this._mediaRecorder)||void 0===t?void 0:t.state)&&(this._stopResolve=null,this._mediaRecorder.stop()),this._audioChunks=[],this._waveformSamples=[],this._timer&&clearInterval(this._timer),cancelAnimationFrame(this._animFrame),this._analyser=null,this.state=Object.assign({},$t),this.host.requestUpdate()}stop(){return _t(this,void 0,void 0,function*(){var t;if(!this._mediaRecorder||"recording"!==this._mediaRecorder.state)return null;const e=this.state.duration,n=yield new Promise(t=>{this._stopResolve=t,this._mediaRecorder.stop()});yield new Promise(t=>setTimeout(t,200)),this.state=Object.assign({},$t),this.host.requestUpdate();const i=(null===(t=this._mediaRecorder)||void 0===t?void 0:t.mimeType)||"audio/webm",o=new Blob(n,{type:i});this._audioChunks=[],this._waveformSamples=[];try{const{compressToOpus:t}=yield Promise.resolve().then(function(){return Ze}),{blob:n,mimeType:s}=yield t(o,i);return{blob:n,mimeType:s,duration:e}}catch(t){return{blob:o,mimeType:i,duration:e}}})}}
|
|
2359
2590
|
/**
|
|
2360
2591
|
* @license
|
|
2361
2592
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2362
2593
|
* SPDX-License-Identifier: MIT
|
|
2363
|
-
*/var xt=function(t,e,n,i){for(var o,s=arguments.length,r=s<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i,a=t.length-1;a>=0;a--)(o=t[a])&&(r=(s<3?o(r):s>3?o(e,n,r):o(e,n))||r);return s>3&&r&&Object.defineProperty(e,n,r),r},wt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};let _t=class extends((t=>N(D(L(W(t)))))(i)){constructor(){super(...arguments),this.requiredComponents=["nr-input","nr-button","nr-icon","nr-dropdown","nr-select","nr-modal","nr-popconfirm"],this.messages=[],this.currentInput="",this.isBotTyping=!1,this.isQueryRunning=!1,this.suggestions=[],this.chatStarted=!1,this.isRTL=!1,this.size=V.Medium,this.variant=G.Default,this.loadingIndicator=q.Dots,this.loadingText=f("Agent is working..."),this.disabled=!1,this.placeholder=f("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=f("Select Modules"),this.enableArtifacts=!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._artifactResizeBound=!1,this.toggleThreadSidebar=()=>{this.isThreadSidebarOpen=!this.isThreadSidebarOpen}}get moduleSelectOptions(){return this.modules.map(t=>({value:t.id,label:t.name,icon:t.icon,disabled:!1===t.enabled,description:t.description}))}connectedCallback(){super.connectedCallback(),this.controller&&this.setupControllerIntegration(),this.setupUrlSync()}firstUpdated(){var t,e,n,i;null===(t=this.shadowRoot)||void 0===t||t.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(i){const t=i.dataset.artifactId;t&&this.handleArtifactClick(t)}}),null===(e=this.shadowRoot)||void 0===e||e.addEventListener("nr-thread-edit",t=>{const e=t.detail;(null==e?void 0:e.threadId)&&(this._editingThreadId=e.threadId,this.requestUpdate(),this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".thread-item__rename-input");e&&(e.focus(),e.select())}))}),null===(n=this.shadowRoot)||void 0===n||n.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-selection-value]");if(i){const t=i.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}}),null===(i=this.shadowRoot)||void 0===i||i.addEventListener("keydown",t=>{var e,n,i,o;const s=t;if("Enter"!==s.key&&" "!==s.key)return;const r=null===(n=(e=s.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(r){s.preventDefault();const t=r.dataset.artifactId;return void(t&&this.handleArtifactClick(t))}const a=null===(o=(i=s.target).closest)||void 0===o?void 0:o.call(i,"[data-selection-value]");if(a){s.preventDefault();const t=a.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}})}disconnectedCallback(){var t;super.disconnectedCallback(),this.controller&&this.cleanupControllerIntegration(),this.teardownUrlSync(),null===(t=this._artifactResizeCleanup)||void 0===t||t.call(this),this._artifactResizeBound=!1}updated(t){if(super.updated(t),t.has("controller")&&(this.cleanupControllerIntegration(),this.controller)){this.setupControllerIntegration();try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}this.enableUrlSync&&this.handleHashChange()}if(t.has("enableUrlSync")&&(this.enableUrlSync?this.setupUrlSync():this.teardownUrlSync()),this.controller&&!t.has("controller")){if(t.has("messages")||t.has("suggestions")||t.has("threads"))try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}}t.has("messages")&&this.autoScroll&&this.messages.length>0&&this.scrollToLatestMessage(),this.updateArtifactPanelResize()}scrollToLatestMessage(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&(e.scrollTop=e.scrollHeight)})}setupControllerIntegration(){this.controller&&this.controllerUnsubscribes.push(this.controller.on("state:changed",this.handleControllerStateChange.bind(this)),this.controller.on("message:sent",this.handleControllerMessageSent.bind(this)),this.controller.on("message:received",this.handleControllerMessageReceived.bind(this)),this.controller.on("error",this.handleControllerError.bind(this)))}cleanupControllerIntegration(){if(this.controllerUnsubscribes.length)try{this.controllerUnsubscribes.forEach(t=>{try{t()}catch(t){}})}finally{this.controllerUnsubscribes=[]}}setupUrlSync(){this.enableUrlSync&&!this._hashChangeHandler&&(this._hashChangeHandler=this.handleHashChange.bind(this),window.addEventListener("hashchange",this._hashChangeHandler),this.handleHashChange())}teardownUrlSync(){this._hashChangeHandler&&(window.removeEventListener("hashchange",this._hashChangeHandler),this._hashChangeHandler=void 0)}handleHashChange(){const t=window.location.hash.match(/^#conversation\/(.+)$/);if(t){const e=decodeURIComponent(t[1]);e!==this.activeThreadId&&this.controller&&this.controller.switchThread(e)}}handleControllerStateChange(t){var e,n,i,o,s;if(t.messages&&(this.messages=t.messages),t.threads&&(this.threads=t.threads),t.suggestions&&t.suggestions.length>0&&(this.suggestions=t.suggestions),t.currentThreadId&&(this.activeThreadId=t.currentThreadId),this.enableUrlSync&&t.currentThreadId){const e=`#conversation/${encodeURIComponent(t.currentThreadId)}`;window.location.hash!==e&&history.replaceState(null,"",e)}if(this.chatStarted=(null===(e=t.messages)||void 0===e?void 0:e.length)>0,this.isBotTyping=t.isTyping||!1,this.statusText=t.statusText,this.isQueryRunning=t.isProcessing||!1,t.uploadedFiles&&(this.uploadedFiles=t.uploadedFiles),this.enableArtifacts){const e=null===(n=t.messages)||void 0===n?void 0:n.some(t=>{var e,n;return(null===(n=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds)||void 0===n?void 0:n.length)>0});e||(this.isArtifactPanelOpen=!1,this.selectedArtifact=null)}if(this.enableArtifacts&&(null===(i=t.messages)||void 0===i?void 0:i.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),n=null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.artifactIds;if(null==n?void 0:n.length){const t=n[n.length-1];if((null===(s=this.selectedArtifact)||void 0===s?void 0:s.id)!==t){const e=this.getArtifactPlugin(),n=null==e?void 0:e.getArtifact(t);n&&(this.selectedArtifact=n,this.isArtifactPanelOpen=!0)}}}}handleControllerMessageSent(t){this.isQueryRunning=!0,this.isBotTyping=!0}handleControllerMessageReceived(t){}handleControllerError(t){this.isQueryRunning=!1,this.isBotTyping=!1,console.error("Controller error:",t.error)}render(){var t;const e={boxed:this.boxed,showMessages:this.showMessages,messages:this.messages,isTyping:this.isBotTyping,loadingIndicator:this.loadingIndicator,loadingText:this.statusText||this.loadingText,chatStarted:this.chatStarted,suggestions:this.suggestions,inputBox:{placeholder:this.placeholder,disabled:this.disabled||this.isQueryRunning,currentInput:this.currentInput,uploadedFiles:this.uploadedFiles,isQueryRunning:this.isQueryRunning,showSendButton:this.showSendButton,enableFileUpload:this.enableFileUpload,fileUploadItems:[{id:"upload-file",label:"Upload File",icon:"upload"},{id:"upload-url",label:"Upload from URL",icon:"link"}],enableModuleSelection:this.enableModuleSelection,moduleOptions:this.moduleSelectOptions,selectedModules:this.selectedModules,moduleSelectionLabel:this.moduleSelectionLabel,renderModuleDisplay:this.renderModuleSelectedDisplay.bind(this)},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId}:void 0,isDragging:!1,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer()}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName}:void 0},i={message:{onRetry:this.handleRetry.bind(this),onRetryKeydown:()=>{},onCopy:this.handleCopyMessage.bind(this),onCopyKeydown:()=>{},onFileClick:this.handleFilePreview.bind(this)},suggestion:{onClick:this.handleSuggestionClick.bind(this),onKeydown:()=>{}},inputBox:{onInput:this.handleContentEditableInput.bind(this),onKeydown:this.handleKeyDown.bind(this),onFocus:this.handleInputFocus.bind(this),onBlur:this.handleInputBlur.bind(this),onSend:this.handleSendMessage.bind(this),onStop:this.handleStopQuery.bind(this),onSendKeydown:()=>{},onFileDropdownClick:this.handleFileDropdownClick.bind(this),onModuleChange:this.handleModuleSelectionChange.bind(this),onFileRemove:this.handleFileRemove.bind(this),onFileClick:this.handleFilePreview.bind(this)},threadSidebar:this.showThreads?{onCreateNew:()=>{var t;null===(t=this.controller)||void 0===t||t.createThread("New Chat")},onSelectThread:t=>{var e;this.enableUrlSync&&history.pushState(null,"",`#conversation/${encodeURIComponent(t)}`),null===(e=this.controller)||void 0===e||e.switchThread(t)},onDeleteThread:t=>{var e;null===(e=this.controller)||void 0===e||e.deleteThread(t)},onBookmarkThread:t=>{var e;null===(e=this.controller)||void 0===e||e.bookmarkThread(t)},onRenameThread:(t,e)=>{var n;null===(n=this.controller)||void 0===n||n.renameThread(t,e),this._editingThreadId=void 0}}:void 0,fileUploadArea:{onDrop:()=>{},onDragOver:()=>{},onDragLeave:()=>{}},urlModal:this.isUrlModalOpen?{onClose:this.handleUrlModalClose.bind(this),onUrlInputChange:this.handleUrlInputChange.bind(this),onUrlInputKeydown:this.handleUrlInputKeydown.bind(this),onConfirm:this.handleUrlConfirm.bind(this),onAttachFile:this.handleUrlAttachFile.bind(this)}:void 0,artifactPanel:this.enableArtifacts?{onClose:this.handleArtifactPanelClose.bind(this),onCopy:this.handleArtifactCopy.bind(this)}:void 0,onToggleThreadSidebar:this.showThreads?this.toggleThreadSidebar.bind(this):void 0};return n`
|
|
2594
|
+
*/var St=function(t,e,n,i){for(var o,s=arguments.length,r=s<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i,a=t.length-1;a>=0;a--)(o=t[a])&&(r=(s<3?o(r):s>3?o(e,n,r):o(e,n))||r);return s>3&&r&&Object.defineProperty(e,n,r),r},Pt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};let Mt=class extends((t=>B(F(L(H(t)))))(i)){constructor(){super(...arguments),this.requiredComponents=["nr-input","nr-button","nr-icon","nr-dropdown","nr-select","nr-modal","nr-popconfirm"],this.messages=[],this.currentInput="",this.isBotTyping=!1,this.isQueryRunning=!1,this.suggestions=[],this.chatStarted=!1,this.isRTL=!1,this.size=G.Medium,this.variant=K.Default,this.loadingIndicator=V.Dots,this.loadingText=g("Agent is working..."),this.disabled=!1,this.placeholder=g("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=g("Select Modules"),this.enableArtifacts=!1,this.showAudioButton=!1,this.focused=!1,this.isArtifactPanelOpen=!1,this.selectedArtifact=null,this.isThreadSidebarOpen=!0,this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName="",this.isFilePreviewModalOpen=!1,this.previewFile=null,this.controllerUnsubscribes=[],this._audio=new kt(this),this._audioMode="message",this._artifactResizeBound=!1,this.toggleThreadSidebar=()=>{this.isThreadSidebarOpen=!this.isThreadSidebarOpen}}get moduleSelectOptions(){return this.modules.map(t=>({value:t.id,label:t.name,icon:t.icon,disabled:!1===t.enabled,description:t.description}))}connectedCallback(){super.connectedCallback(),this.controller&&this.setupControllerIntegration(),this.setupUrlSync()}firstUpdated(){var t,e,n,i;null===(t=this.shadowRoot)||void 0===t||t.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(i){const t=i.dataset.artifactId;t&&this.handleArtifactClick(t)}}),null===(e=this.shadowRoot)||void 0===e||e.addEventListener("nr-thread-edit",t=>{const e=t.detail;(null==e?void 0:e.threadId)&&(this._editingThreadId=e.threadId,this.requestUpdate(),this.updateComplete.then(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".thread-item__rename-input");e&&(e.focus(),e.select())}))}),null===(n=this.shadowRoot)||void 0===n||n.addEventListener("click",t=>{var e,n;const i=null===(n=(e=t.target).closest)||void 0===n?void 0:n.call(e,"[data-selection-value]");if(i){const t=i.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}}),null===(i=this.shadowRoot)||void 0===i||i.addEventListener("keydown",t=>{var e,n,i,o;const s=t;if("Enter"!==s.key&&" "!==s.key)return;const r=null===(n=(e=s.target).closest)||void 0===n?void 0:n.call(e,"[data-artifact-id]");if(r){s.preventDefault();const t=r.dataset.artifactId;return void(t&&this.handleArtifactClick(t))}const a=null===(o=(i=s.target).closest)||void 0===o?void 0:o.call(i,"[data-selection-value]");if(a){s.preventDefault();const t=a.dataset.selectionValue;t&&this.controller&&this.controller.sendMessage(t)}})}disconnectedCallback(){var t;super.disconnectedCallback(),this.controller&&this.cleanupControllerIntegration(),this.teardownUrlSync(),null===(t=this._artifactResizeCleanup)||void 0===t||t.call(this),this._artifactResizeBound=!1}updated(t){if(super.updated(t),t.has("controller")&&(this.cleanupControllerIntegration(),this.controller)){this.setupControllerIntegration();try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}this.enableUrlSync&&this.handleHashChange()}if(t.has("enableUrlSync")&&(this.enableUrlSync?this.setupUrlSync():this.teardownUrlSync()),this.controller&&!t.has("controller")){if(t.has("messages")||t.has("suggestions")||t.has("threads"))try{const t=this.controller.getState();this.handleControllerStateChange(t)}catch(t){}}t.has("messages")&&this.autoScroll&&this.messages.length>0&&this.scrollToLatestMessage(),this.updateArtifactPanelResize()}scrollToLatestMessage(){requestAnimationFrame(()=>{var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&(e.scrollTop=e.scrollHeight)})}setupControllerIntegration(){this.controller&&this.controllerUnsubscribes.push(this.controller.on("state:changed",this.handleControllerStateChange.bind(this)),this.controller.on("message:sent",this.handleControllerMessageSent.bind(this)),this.controller.on("message:received",this.handleControllerMessageReceived.bind(this)),this.controller.on("error",this.handleControllerError.bind(this)))}cleanupControllerIntegration(){if(this.controllerUnsubscribes.length)try{this.controllerUnsubscribes.forEach(t=>{try{t()}catch(t){}})}finally{this.controllerUnsubscribes=[]}}setupUrlSync(){this.enableUrlSync&&!this._hashChangeHandler&&(this._hashChangeHandler=this.handleHashChange.bind(this),window.addEventListener("hashchange",this._hashChangeHandler),this.handleHashChange())}teardownUrlSync(){this._hashChangeHandler&&(window.removeEventListener("hashchange",this._hashChangeHandler),this._hashChangeHandler=void 0)}handleHashChange(){const t=window.location.hash.match(/^#conversation\/(.+)$/);if(t){const e=decodeURIComponent(t[1]);e!==this.activeThreadId&&this.controller&&this.controller.switchThread(e)}}handleControllerStateChange(t){var e,n,i,o,s;if(t.messages&&(this.messages=t.messages),t.threads&&(this.threads=t.threads),t.suggestions&&t.suggestions.length>0&&(this.suggestions=t.suggestions),t.currentThreadId&&(this.activeThreadId=t.currentThreadId),this.enableUrlSync&&t.currentThreadId){const e=`#conversation/${encodeURIComponent(t.currentThreadId)}`;window.location.hash!==e&&history.replaceState(null,"",e)}if(this.chatStarted=(null===(e=t.messages)||void 0===e?void 0:e.length)>0,this.isBotTyping=t.isTyping||!1,this.statusText=t.statusText,this.isQueryRunning=t.isProcessing||!1,t.uploadedFiles&&(this.uploadedFiles=t.uploadedFiles),this.enableArtifacts){const e=null===(n=t.messages)||void 0===n?void 0:n.some(t=>{var e,n;return(null===(n=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds)||void 0===n?void 0:n.length)>0});e||(this.isArtifactPanelOpen=!1,this.selectedArtifact=null)}if(this.enableArtifacts&&(null===(i=t.messages)||void 0===i?void 0:i.length)){const e=[...t.messages].reverse().find(t=>"bot"===t.sender),n=null===(o=null==e?void 0:e.metadata)||void 0===o?void 0:o.artifactIds;if(null==n?void 0:n.length){const t=n[n.length-1];if((null===(s=this.selectedArtifact)||void 0===s?void 0:s.id)!==t){const e=this.getArtifactPlugin(),n=null==e?void 0:e.getArtifact(t);n&&(this.selectedArtifact=n,this.isArtifactPanelOpen=!0)}}}}handleControllerMessageSent(t){this.isQueryRunning=!0,this.isBotTyping=!0}handleControllerMessageReceived(t){}handleControllerError(t){this.isQueryRunning=!1,this.isBotTyping=!1,console.error("Controller error:",t.error)}render(){var t;const e={boxed:this.boxed,showMessages:this.showMessages,messages:this.messages,isTyping:this.isBotTyping,loadingIndicator:this.loadingIndicator,loadingText:this.statusText||this.loadingText,chatStarted:this.chatStarted,suggestions:this.suggestions,inputBox:{placeholder:this.placeholder,disabled:this.disabled||this.isQueryRunning,currentInput:this.currentInput,uploadedFiles:this.uploadedFiles,isQueryRunning:this.isQueryRunning,showSendButton:this.showSendButton,enableFileUpload:this.enableFileUpload,fileUploadItems:[{id:"upload-file",label:"Upload File",icon:"upload"},{id:"upload-url",label:"Upload from URL",icon:"link"}],enableModuleSelection:this.enableModuleSelection,moduleOptions:this.moduleSelectOptions,selectedModules:this.selectedModules,moduleSelectionLabel:this.moduleSelectionLabel,renderModuleDisplay:this.renderModuleSelectedDisplay.bind(this),showAudioButton:this.showAudioButton,audioRecording:this._audio.state,audioMode:this._audioMode},enableThreads:this.showThreads,enableThreadCreation:this.enableThreadCreation,isThreadSidebarOpen:this.showThreads&&this.isThreadSidebarOpen,threadSidebar:this.showThreads?{threads:this.threads,activeThreadId:this.activeThreadId,editingThreadId:this._editingThreadId}:void 0,isDragging:!1,enableArtifacts:this.enableArtifacts,artifactPanel:this.enableArtifacts?{artifact:this.selectedArtifact,isOpen:this.isArtifactPanelOpen,renderContent:null!==(t=this.renderArtifactContent)&&void 0!==t?t:this.getPluginArtifactRenderer()}:void 0,urlModal:this.isUrlModalOpen?{isOpen:this.isUrlModalOpen,urlInput:this.urlInput,isLoading:this.isUrlLoading,error:this.urlModalError,selectedFileName:this.selectedUrlFileName}:void 0},i={message:{onRetry:this.handleRetry.bind(this),onRetryKeydown:()=>{},onCopy:this.handleCopyMessage.bind(this),onCopyKeydown:()=>{},onFileClick:this.handleFilePreview.bind(this)},suggestion:{onClick:this.handleSuggestionClick.bind(this),onKeydown:()=>{}},inputBox:{onInput:this.handleContentEditableInput.bind(this),onKeydown:this.handleKeyDown.bind(this),onFocus:this.handleInputFocus.bind(this),onBlur:this.handleInputBlur.bind(this),onSend:this.handleSendMessage.bind(this),onStop:this.handleStopQuery.bind(this),onSendKeydown:()=>{},onFileDropdownClick:this.handleFileDropdownClick.bind(this),onModuleChange:this.handleModuleSelectionChange.bind(this),onFileRemove:this.handleFileRemove.bind(this),onFileClick:this.handleFilePreview.bind(this),onAudioStart:this.handleAudioStart.bind(this),onAudioCancel:this.handleAudioCancel.bind(this),onAudioSend:this.handleAudioSend.bind(this)},threadSidebar:this.showThreads?{onCreateNew:()=>{var t;null===(t=this.controller)||void 0===t||t.createThread("New Chat")},onSelectThread:t=>{var e;this.enableUrlSync&&history.pushState(null,"",`#conversation/${encodeURIComponent(t)}`),null===(e=this.controller)||void 0===e||e.switchThread(t)},onDeleteThread:t=>{var e;null===(e=this.controller)||void 0===e||e.deleteThread(t)},onBookmarkThread:t=>{var e;null===(e=this.controller)||void 0===e||e.bookmarkThread(t)},onRenameThread:(t,e)=>{var n;null===(n=this.controller)||void 0===n||n.renameThread(t,e),this._editingThreadId=void 0}}:void 0,fileUploadArea:{onDrop:()=>{},onDragOver:()=>{},onDragLeave:()=>{}},urlModal:this.isUrlModalOpen?{onClose:this.handleUrlModalClose.bind(this),onUrlInputChange:this.handleUrlInputChange.bind(this),onUrlInputKeydown:this.handleUrlInputKeydown.bind(this),onConfirm:this.handleUrlConfirm.bind(this),onAttachFile:this.handleUrlAttachFile.bind(this)}:void 0,artifactPanel:this.enableArtifacts?{onClose:this.handleArtifactPanelClose.bind(this),onCopy:this.handleArtifactCopy.bind(this)}:void 0,onToggleThreadSidebar:this.showThreads?this.toggleThreadSidebar.bind(this):void 0};return n`
|
|
2364
2595
|
<div
|
|
2365
2596
|
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})}"
|
|
2366
2597
|
dir=${this.isRTL?"rtl":"ltr"}
|
|
@@ -2370,10 +2601,10 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2370
2601
|
data-mode="${this.mode}"
|
|
2371
2602
|
part="chat-container">
|
|
2372
2603
|
|
|
2373
|
-
${
|
|
2604
|
+
${wt(e,i)}
|
|
2374
2605
|
</div>
|
|
2375
2606
|
|
|
2376
|
-
${
|
|
2607
|
+
${bt({isOpen:this.isFilePreviewModalOpen,file:this.previewFile},{onClose:this.handleFilePreviewModalClose.bind(this)})}
|
|
2377
2608
|
`}renderModuleSelectedDisplay(){const t=this.selectedModules.length;if(0===t)return n`<span class="module-display-placeholder">${this.moduleSelectionLabel}</span>`;if(1===t){const t=this.modules.find(t=>t.id===this.selectedModules[0]);return n`
|
|
2378
2609
|
<span class="module-display-single">
|
|
2379
2610
|
${(null==t?void 0:t.icon)?n`<nr-icon name="${t.icon}" size="small"></nr-icon>`:e}
|
|
@@ -2381,163 +2612,176 @@ function(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(102
|
|
|
2381
2612
|
</span>
|
|
2382
2613
|
`}return n`
|
|
2383
2614
|
<span class="module-display-multiple">
|
|
2384
|
-
${t} ${
|
|
2615
|
+
${t} ${g("modules selected")}
|
|
2385
2616
|
</span>
|
|
2386
|
-
`}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()}handleKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendMessage())}handleSendMessage(){if(!this.currentInput.trim()||this.disabled)return;if(!this.controller)return void console.warn("nr-chatbot: No controller is attached; message will not be sent.");const t=this.uploadedFiles&&this.uploadedFiles.length>0?[...this.uploadedFiles]:void 0;this.controller.sendMessage(this.currentInput.trim(),{files:t,metadata:{selectedModules:this.selectedModules}}),this.clearInput(),this.chatStarted=!0,this.dispatchEventWithMetadata("nr-chatbot-message-sent",{metadata:{text:this.currentInput}})}handleStopQuery(){var t;try{null===(t=this.controller)||void 0===t||t.stop()}catch(t){console.warn("nr-chatbot: stop failed",t)}this.dispatchEventWithMetadata("nr-chatbot-query-stopped",{metadata:{action:"stop"}})}handleRetry(t){t.text&&(this.currentInput=t.text,this.handleSendMessage())}handleCopyMessage(t){const e=t.text;if(!e)return;const n=()=>{this.dispatchEventWithMetadata("nr-chatbot-message-copied",{metadata:{messageId:t.id}})};navigator.clipboard?navigator.clipboard.writeText(e).then(n).catch(()=>{this.copyViaFallback(e,n)}):this.copyViaFallback(e,n)}copyViaFallback(t,e){const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-9999px",n.style.top="-9999px",document.body.appendChild(n),n.focus(),n.select();try{document.execCommand("copy"),e()}catch(t){}n.remove()}handleSuggestionClick(t){this.currentInput=t.text,this.handleSendMessage(),this.dispatchEventWithMetadata("nr-chatbot-suggestion-clicked",{metadata:{suggestion:t}})}handleModuleSelectionChange(t){const e=t.detail.value;this.selectedModules=e,this.dispatchEventWithMetadata("nr-chatbot-modules-selected",{metadata:{modules:e}})}handleFileDropdownClick(t){const e=t.detail.item.id;"upload-file"===e?this.openFileDialog():"upload-url"===e&&this.openUrlModal()}openFileDialog(){const t=document.createElement("input");t.type="file",t.multiple=!0,t.accept="image/*,application/pdf,text/*,video/*,audio/*",t.addEventListener("change",t=>wt(this,void 0,void 0,function*(){var e;const n=t.target;if(n.files&&n.files.length>0){const t=Array.from(n.files);yield null===(e=this.controller)||void 0===e?void 0:e.uploadFiles(t)}})),t.click()}openUrlModal(){this.isUrlModalOpen=!0,this.urlInput="",this.urlModalError="",this.selectedUrlFileName=""}handleUrlModalClose(){this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName=""}handleUrlInputChange(t){const e=t.target;this.urlInput=e.value,this.urlModalError=""}handleUrlInputKeydown(t){"Enter"===t.key&&(t.preventDefault(),this.handleUrlAttachFile())}handleUrlConfirm(){this.handleUrlModalClose()}handleUrlAttachFile(){return wt(this,void 0,void 0,function*(){if(this.urlInput.trim()){this.isUrlLoading=!0,this.urlModalError="";try{const t=yield fetch(this.urlInput);if(!t.ok)throw new Error(`Failed to fetch file: ${t.statusText}`);const e=yield t.blob(),n=this.urlInput.split("/").pop()||"downloaded-file",i=new File([e],n,{type:e.type});this.selectedUrlFileName=n,this.controller&&(yield this.controller.uploadFiles([i])),this.isUrlLoading=!1,setTimeout(()=>{this.handleUrlModalClose()},1e3)}catch(t){this.isUrlLoading=!1,this.urlModalError=t instanceof Error?t.message:"Failed to load file from URL"}}else this.urlModalError="Please enter a URL"})}handleFileRemove(t){var e;null===(e=this.controller)||void 0===e||e.removeFile(t)}handleFilePreview(t){this.previewFile=t,this.isFilePreviewModalOpen=!0}handleArtifactClick(t){if(!this.enableArtifacts||!this.controller)return;const e=this.getArtifactPlugin();if(!e)return;const n=e.getArtifact(t);n&&(this.selectedArtifact=n,this.isArtifactPanelOpen=!0)}handleArtifactPanelClose(){this.isArtifactPanelOpen=!1,this.selectedArtifact=null}updateArtifactPanelResize(){var t,e,n;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".artifact-panel__resize-handle"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".artifact-panel");if(!i||!o)return null===(n=this._artifactResizeCleanup)||void 0===n||n.call(this),void(this._artifactResizeBound=!1);if(this._artifactResizeBound)return;this._artifactResizeBound=!0;let s=!1,r=0,a=0;const l=t=>{if(!s)return;const e=t.clientX-r,n=o.parentElement,i=n?.85*n.getBoundingClientRect().width:1200,l=Number.parseInt(getComputedStyle(o).minWidth,10)||300,d=Math.max(l,Math.min(a-e,i));o.style.width=`${d}px`},d=()=>{s&&(s=!1,i.classList.remove("artifact-panel__resize-handle--active"),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",d))},c=t=>{t.preventDefault(),s=!0,r=t.clientX,a=o.getBoundingClientRect().width,i.classList.add("artifact-panel__resize-handle--active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",l),document.addEventListener("mouseup",d)};i.addEventListener("mousedown",c),this._artifactResizeCleanup=()=>{i.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 i=t.renderArtifactContent(e);if(i)return n`${l(i)}`};return}catch(t){return}}handleFilePreviewModalClose(){this.isFilePreviewModalOpen=!1,this.previewFile=null}addMessage(t){var e;const n=Object.assign({id:t.id||`msg-${Date.now()}`,sender:t.sender||J.User,text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t);return null===(e=this.controller)||void 0===e||e.addMessage(n),this.chatStarted=!0,n}clearMessages(){this.messages=[],this.chatStarted=!1}};_t.useShadowDom=!0,_t.styles=A,xt([o({type:Array})],_t.prototype,"messages",void 0),xt([o({type:String})],_t.prototype,"currentInput",void 0),xt([o({type:Boolean})],_t.prototype,"isBotTyping",void 0),xt([o({type:Boolean})],_t.prototype,"isQueryRunning",void 0),xt([o({type:Array})],_t.prototype,"suggestions",void 0),xt([o({type:Boolean})],_t.prototype,"chatStarted",void 0),xt([o({type:Boolean})],_t.prototype,"isRTL",void 0),xt([o({type:String})],_t.prototype,"size",void 0),xt([o({type:String})],_t.prototype,"variant",void 0),xt([o({type:String})],_t.prototype,"loadingIndicator",void 0),xt([o({type:String})],_t.prototype,"loadingText",void 0),xt([o({type:Boolean})],_t.prototype,"disabled",void 0),xt([o({type:String})],_t.prototype,"placeholder",void 0),xt([o({type:Boolean})],_t.prototype,"showSendButton",void 0),xt([o({type:Boolean})],_t.prototype,"autoScroll",void 0),xt([o({type:Boolean})],_t.prototype,"showThreads",void 0),xt([o({type:Boolean})],_t.prototype,"enableThreadCreation",void 0),xt([o({type:Array})],_t.prototype,"threads",void 0),xt([o({type:String})],_t.prototype,"activeThreadId",void 0),xt([o({type:String})],_t.prototype,"mode",void 0),xt([o({type:Boolean,reflect:!0})],_t.prototype,"boxed",void 0),xt([o({type:Boolean})],_t.prototype,"enableUrlSync",void 0),xt([o({type:Boolean})],_t.prototype,"showMessages",void 0),xt([o({type:Boolean})],_t.prototype,"enableFileUpload",void 0),xt([o({type:Array})],_t.prototype,"uploadedFiles",void 0),xt([o({type:Array})],_t.prototype,"actionButtons",void 0),xt([o({type:Boolean})],_t.prototype,"enableModuleSelection",void 0),xt([o({type:Array})],_t.prototype,"modules",void 0),xt([o({type:Array})],_t.prototype,"selectedModules",void 0),xt([o({type:String})],_t.prototype,"moduleSelectionLabel",void 0),xt([o({type:Boolean})],_t.prototype,"enableArtifacts",void 0),xt([o({type:Function})],_t.prototype,"renderArtifactContent",void 0),xt([o({type:Object})],_t.prototype,"controller",void 0),xt([s()],_t.prototype,"statusText",void 0),xt([s()],_t.prototype,"focused",void 0),xt([s()],_t.prototype,"isArtifactPanelOpen",void 0),xt([s()],_t.prototype,"selectedArtifact",void 0),xt([s()],_t.prototype,"isThreadSidebarOpen",void 0),xt([s()],_t.prototype,"_editingThreadId",void 0),xt([s()],_t.prototype,"isUrlModalOpen",void 0),xt([s()],_t.prototype,"urlInput",void 0),xt([s()],_t.prototype,"urlModalError",void 0),xt([s()],_t.prototype,"isUrlLoading",void 0),xt([s()],_t.prototype,"selectedUrlFileName",void 0),xt([s()],_t.prototype,"isFilePreviewModalOpen",void 0),xt([s()],_t.prototype,"previewFile",void 0),_t=xt([(t,e)=>(t.addInitializer(v),t),r("nr-chatbot")],_t);
|
|
2617
|
+
`}handleContentEditableInput(t){const e=t.target.textContent||"";this.currentInput=e,this.dispatchEventWithMetadata("nr-chatbot-input-changed",{metadata:{value:e}})}handleInputFocus(t){this.focused=!0,this.dispatchEventWithMetadata("nr-chatbot-input-focused",{metadata:{event:t}})}handleInputBlur(t){this.focused=!1,this.dispatchEventWithMetadata("nr-chatbot-input-blurred",{metadata:{event:t}})}clearInput(){var t;this.currentInput="";const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&(e.textContent="")}focusInput(){var t;const e=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".input-box__input");e&&e.focus()}handleAudioStart(t){this._audioMode=t,this._audio.start()}handleAudioCancel(){this._audio.cancel()}handleAudioSend(){return Pt(this,void 0,void 0,function*(){var t;const e=yield this._audio.stop();if(!e)return;const n=this._audioMode;null===(t=this.onAudioRecorded)||void 0===t||t.call(this,e.blob,e.mimeType,e.duration,n),this.dispatchEvent(new CustomEvent("nr-chatbot-audio-recorded",{detail:{blob:e.blob,mimeType:e.mimeType,duration:e.duration,mode:n},bubbles:!0,composed:!0}))})}handleKeyDown(t){"Enter"!==t.key||t.shiftKey||(t.preventDefault(),this.handleSendMessage())}handleSendMessage(){if(!this.currentInput.trim()||this.disabled)return;if(!this.controller)return void console.warn("nr-chatbot: No controller is attached; message will not be sent.");const t=this.uploadedFiles&&this.uploadedFiles.length>0?[...this.uploadedFiles]:void 0;this.controller.sendMessage(this.currentInput.trim(),{files:t,metadata:{selectedModules:this.selectedModules}}),this.clearInput(),this.chatStarted=!0,this.dispatchEventWithMetadata("nr-chatbot-message-sent",{metadata:{text:this.currentInput}})}handleStopQuery(){var t;try{null===(t=this.controller)||void 0===t||t.stop()}catch(t){console.warn("nr-chatbot: stop failed",t)}this.dispatchEventWithMetadata("nr-chatbot-query-stopped",{metadata:{action:"stop"}})}handleRetry(t){t.text&&(this.currentInput=t.text,this.handleSendMessage())}handleCopyMessage(t){const e=t.text;if(!e)return;const n=()=>{this.dispatchEventWithMetadata("nr-chatbot-message-copied",{metadata:{messageId:t.id}})};navigator.clipboard?navigator.clipboard.writeText(e).then(n).catch(()=>{this.copyViaFallback(e,n)}):this.copyViaFallback(e,n)}copyViaFallback(t,e){const n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.left="-9999px",n.style.top="-9999px",document.body.appendChild(n),n.focus(),n.select();try{document.execCommand("copy"),e()}catch(t){}n.remove()}handleSuggestionClick(t){this.currentInput=t.text,this.handleSendMessage(),this.dispatchEventWithMetadata("nr-chatbot-suggestion-clicked",{metadata:{suggestion:t}})}handleModuleSelectionChange(t){const e=t.detail.value;this.selectedModules=e,this.dispatchEventWithMetadata("nr-chatbot-modules-selected",{metadata:{modules:e}})}handleFileDropdownClick(t){const e=t.detail.item.id;"upload-file"===e?this.openFileDialog():"upload-url"===e&&this.openUrlModal()}openFileDialog(){const t=document.createElement("input");t.type="file",t.multiple=!0,t.accept="image/*,application/pdf,text/*,video/*,audio/*",t.addEventListener("change",t=>Pt(this,void 0,void 0,function*(){var e;const n=t.target;if(n.files&&n.files.length>0){const t=Array.from(n.files);yield null===(e=this.controller)||void 0===e?void 0:e.uploadFiles(t)}})),t.click()}openUrlModal(){this.isUrlModalOpen=!0,this.urlInput="",this.urlModalError="",this.selectedUrlFileName=""}handleUrlModalClose(){this.isUrlModalOpen=!1,this.urlInput="",this.urlModalError="",this.isUrlLoading=!1,this.selectedUrlFileName=""}handleUrlInputChange(t){const e=t.target;this.urlInput=e.value,this.urlModalError=""}handleUrlInputKeydown(t){"Enter"===t.key&&(t.preventDefault(),this.handleUrlAttachFile())}handleUrlConfirm(){this.handleUrlModalClose()}handleUrlAttachFile(){return Pt(this,void 0,void 0,function*(){if(this.urlInput.trim()){this.isUrlLoading=!0,this.urlModalError="";try{const t=yield fetch(this.urlInput);if(!t.ok)throw new Error(`Failed to fetch file: ${t.statusText}`);const e=yield t.blob(),n=this.urlInput.split("/").pop()||"downloaded-file",i=new File([e],n,{type:e.type});this.selectedUrlFileName=n,this.controller&&(yield this.controller.uploadFiles([i])),this.isUrlLoading=!1,setTimeout(()=>{this.handleUrlModalClose()},1e3)}catch(t){this.isUrlLoading=!1,this.urlModalError=t instanceof Error?t.message:"Failed to load file from URL"}}else this.urlModalError="Please enter a URL"})}handleFileRemove(t){var e;null===(e=this.controller)||void 0===e||e.removeFile(t)}handleFilePreview(t){this.previewFile=t,this.isFilePreviewModalOpen=!0}handleArtifactClick(t){if(!this.enableArtifacts||!this.controller)return;const e=this.getArtifactPlugin();if(!e)return;const n=e.getArtifact(t);n&&(this.selectedArtifact=n,this.isArtifactPanelOpen=!0)}handleArtifactPanelClose(){this.isArtifactPanelOpen=!1,this.selectedArtifact=null}updateArtifactPanelResize(){var t,e,n;const i=null===(t=this.shadowRoot)||void 0===t?void 0:t.querySelector(".artifact-panel__resize-handle"),o=null===(e=this.shadowRoot)||void 0===e?void 0:e.querySelector(".artifact-panel");if(!i||!o)return null===(n=this._artifactResizeCleanup)||void 0===n||n.call(this),void(this._artifactResizeBound=!1);if(this._artifactResizeBound)return;this._artifactResizeBound=!0;let s=!1,r=0,a=0;const l=t=>{if(!s)return;const e=t.clientX-r,n=o.parentElement,i=n?.85*n.getBoundingClientRect().width:1200,l=Number.parseInt(getComputedStyle(o).minWidth,10)||300,c=Math.max(l,Math.min(a-e,i));o.style.width=`${c}px`},c=()=>{s&&(s=!1,i.classList.remove("artifact-panel__resize-handle--active"),document.body.style.cursor="",document.body.style.userSelect="",document.removeEventListener("mousemove",l),document.removeEventListener("mouseup",c))},d=t=>{t.preventDefault(),s=!0,r=t.clientX,a=o.getBoundingClientRect().width,i.classList.add("artifact-panel__resize-handle--active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",l),document.addEventListener("mouseup",c)};i.addEventListener("mousedown",d),this._artifactResizeCleanup=()=>{i.removeEventListener("mousedown",d),c()}}handleArtifactCopy(t){const e=t.content;e&&(navigator.clipboard?navigator.clipboard.writeText(e).catch(()=>{this.copyViaFallback(e,()=>{})}):this.copyViaFallback(e,()=>{}))}getArtifactPlugin(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;return e&&"function"==typeof e.get?e.get("artifact"):void 0}catch(t){return}}getPluginArtifactRenderer(){var t;try{const e=null===(t=this.controller)||void 0===t?void 0:t.plugins;if(!e||"function"!=typeof e.values)return;for(const t of e.values())if("function"==typeof t.renderArtifactContent)return e=>{const i=t.renderArtifactContent(e);if(i)return n`${l(i)}`};return}catch(t){return}}handleFilePreviewModalClose(){this.isFilePreviewModalOpen=!1,this.previewFile=null}addMessage(t){var e;const n=Object.assign({id:t.id||`msg-${Date.now()}`,sender:t.sender||q.User,text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t);return null===(e=this.controller)||void 0===e||e.addMessage(n),this.chatStarted=!0,n}clearMessages(){this.messages=[],this.chatStarted=!1}};Mt.useShadowDom=!0,Mt.styles=D,St([o({type:Array})],Mt.prototype,"messages",void 0),St([o({type:String})],Mt.prototype,"currentInput",void 0),St([o({type:Boolean})],Mt.prototype,"isBotTyping",void 0),St([o({type:Boolean})],Mt.prototype,"isQueryRunning",void 0),St([o({type:Array})],Mt.prototype,"suggestions",void 0),St([o({type:Boolean})],Mt.prototype,"chatStarted",void 0),St([o({type:Boolean})],Mt.prototype,"isRTL",void 0),St([o({type:String})],Mt.prototype,"size",void 0),St([o({type:String})],Mt.prototype,"variant",void 0),St([o({type:String})],Mt.prototype,"loadingIndicator",void 0),St([o({type:String})],Mt.prototype,"loadingText",void 0),St([o({type:Boolean})],Mt.prototype,"disabled",void 0),St([o({type:String})],Mt.prototype,"placeholder",void 0),St([o({type:Boolean})],Mt.prototype,"showSendButton",void 0),St([o({type:Boolean})],Mt.prototype,"autoScroll",void 0),St([o({type:Boolean})],Mt.prototype,"showThreads",void 0),St([o({type:Boolean})],Mt.prototype,"enableThreadCreation",void 0),St([o({type:Array})],Mt.prototype,"threads",void 0),St([o({type:String})],Mt.prototype,"activeThreadId",void 0),St([o({type:String})],Mt.prototype,"mode",void 0),St([o({type:Boolean,reflect:!0})],Mt.prototype,"boxed",void 0),St([o({type:Boolean})],Mt.prototype,"enableUrlSync",void 0),St([o({type:Boolean})],Mt.prototype,"showMessages",void 0),St([o({type:Boolean})],Mt.prototype,"enableFileUpload",void 0),St([o({type:Array})],Mt.prototype,"uploadedFiles",void 0),St([o({type:Array})],Mt.prototype,"actionButtons",void 0),St([o({type:Boolean})],Mt.prototype,"enableModuleSelection",void 0),St([o({type:Array})],Mt.prototype,"modules",void 0),St([o({type:Array})],Mt.prototype,"selectedModules",void 0),St([o({type:String})],Mt.prototype,"moduleSelectionLabel",void 0),St([o({type:Boolean})],Mt.prototype,"enableArtifacts",void 0),St([o({type:Boolean,attribute:"show-audio-button"})],Mt.prototype,"showAudioButton",void 0),St([o({type:Function})],Mt.prototype,"onAudioRecorded",void 0),St([o({type:Function})],Mt.prototype,"renderArtifactContent",void 0),St([o({type:Object})],Mt.prototype,"controller",void 0),St([s()],Mt.prototype,"statusText",void 0),St([s()],Mt.prototype,"focused",void 0),St([s()],Mt.prototype,"isArtifactPanelOpen",void 0),St([s()],Mt.prototype,"selectedArtifact",void 0),St([s()],Mt.prototype,"isThreadSidebarOpen",void 0),St([s()],Mt.prototype,"_editingThreadId",void 0),St([s()],Mt.prototype,"isUrlModalOpen",void 0),St([s()],Mt.prototype,"urlInput",void 0),St([s()],Mt.prototype,"urlModalError",void 0),St([s()],Mt.prototype,"isUrlLoading",void 0),St([s()],Mt.prototype,"selectedUrlFileName",void 0),St([s()],Mt.prototype,"isFilePreviewModalOpen",void 0),St([s()],Mt.prototype,"previewFile",void 0),Mt=St([(t,e)=>(t.addInitializer(b),t),r("nr-chatbot")],Mt);
|
|
2387
2618
|
/**
|
|
2388
2619
|
* @license
|
|
2389
2620
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2390
2621
|
* SPDX-License-Identifier: MIT
|
|
2391
2622
|
*/
|
|
2392
|
-
class
|
|
2623
|
+
class Tt{constructor(){this.listeners=new Map}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{var n,i;null===(n=this.listeners.get(t))||void 0===n||n.delete(e),0===(null===(i=this.listeners.get(t))||void 0===i?void 0:i.size)&&this.listeners.delete(t)}}once(t,e){const n=(...i)=>{e(...i),this.off(t,n)};this.on(t,n)}off(t,e){var n;null===(n=this.listeners.get(t))||void 0===n||n.delete(e)}emit(t,e){const n=this.listeners.get(t);n&&n.forEach(n=>{try{n(e)}catch(e){console.error(`Error in event handler for "${t}":`,e)}})}removeAllListeners(t){t?this.listeners.delete(t):this.listeners.clear()}listenerCount(t){var e;return(null===(e=this.listeners.get(t))||void 0===e?void 0:e.size)||0}eventNames(){return Array.from(this.listeners.keys())}}
|
|
2393
2624
|
/**
|
|
2394
2625
|
* @license
|
|
2395
2626
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2396
2627
|
* SPDX-License-Identifier: MIT
|
|
2397
|
-
*/class
|
|
2628
|
+
*/class Et extends Error{constructor(t){super(t.join(", ")),this.errors=t,this.name="ValidationError"}}
|
|
2398
2629
|
/**
|
|
2399
2630
|
* @license
|
|
2400
2631
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2401
2632
|
* SPDX-License-Identifier: MIT
|
|
2402
|
-
*/class
|
|
2633
|
+
*/class Ct{constructor(t,e,n,i,o){this.eventBus=e,this.ui=n,this.plugins=i,this.config=o,this.state=t}getState(){return Object.freeze(Object.assign({},this.state))}updateState(t){if(this.state=Object.assign(Object.assign({},this.state),t),this.ui.onStateChange)try{this.ui.onStateChange(this.getState())}catch(t){this.logError("Error in UI state change callback:",t)}this.eventBus.emit("state:changed",this.state),this.plugins.forEach(t=>{if(t.onStateChange)try{t.onStateChange(this.getState())}catch(t){this.logError("Error in plugin state change handler:",t)}})}addMessageToState(t){this.state.messages=[...this.state.messages,t],t.suggestions&&t.suggestions.length>0?this.state.suggestions=[...t.suggestions]:this.state.messages.length>1&&(this.state.suggestions=[]),this.config.maxMessages&&this.state.messages.length>this.config.maxMessages&&(this.state.messages=this.state.messages.slice(-this.config.maxMessages)),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state),this.ui.scrollToBottom&&this.ui.scrollToBottom(),this.eventBus.emit("message:added",t)}updateMessageInState(t,e){this.state.messages=this.state.messages.map(n=>n.id===t?Object.assign(Object.assign({},n),e):n),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state);const n=this.state.messages.find(e=>e.id===t);n&&this.eventBus.emit("message:updated",n)}removeMessageFromState(t){this.state.messages=this.state.messages.filter(e=>e.id!==t),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.eventBus.emit("state:changed",this.state),this.eventBus.emit("message:deleted",t)}resetState(t){this.state=Object.assign({},t),this.updateState(this.state)}getMessages(){return[...this.state.messages]}getMessageById(t){return this.state.messages.find(e=>e.id===t)}isTyping(){return this.state.isTyping}isProcessing(){return this.state.isProcessing}setTyping(t){this.updateState({isTyping:t}),t&&this.ui.onTypingStart?this.ui.onTypingStart():!t&&this.ui.onTypingEnd&&this.ui.onTypingEnd()}setProcessing(t){this.updateState({isProcessing:t})}logError(t,e){console.error(`[StateHandler] ${t}`,e)}}
|
|
2403
2634
|
/**
|
|
2404
2635
|
* @license
|
|
2405
2636
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2406
2637
|
* SPDX-License-Identifier: MIT
|
|
2407
|
-
*/class
|
|
2638
|
+
*/class zt{constructor(t,e,n){this.stateHandler=t,this.eventBus=e,this.plugins=n}createMessage(t){return Object.assign({id:this.generateId("msg"),sender:t.sender||"user",text:t.text||"",timestamp:t.timestamp||(new Date).toISOString()},t)}createUserMessage(t,e){return this.createMessage({sender:"user",text:t,metadata:e})}createBotMessage(t,e){return this.createMessage({sender:"bot",text:t,metadata:e})}addMessage(t){const e=this.createMessage(t);return this.stateHandler.addMessageToState(e),"bot"===e.sender?(this.eventBus.emit("message:received",e),this.plugins.forEach(t=>{t.onMessageReceived&&t.onMessageReceived(e)})):(this.eventBus.emit("message:sent",e),this.plugins.forEach(t=>{t.onMessageSent&&t.onMessageSent(e)})),e}updateMessage(t,e){this.stateHandler.updateMessageInState(t,e)}deleteMessage(t){this.stateHandler.removeMessageFromState(t)}clearMessages(){this.stateHandler.updateState({messages:[]})}getMessages(){return this.stateHandler.getMessages()}getMessageById(t){return this.stateHandler.getMessageById(t)}updateBotMessageText(t,e){const n=this.getMessageById(t);n&&"bot"===n.sender&&this.updateMessage(t,{text:e})}appendToBotMessage(t,e){const n=this.getMessageById(t);n&&"bot"===n.sender&&this.updateMessage(t,{text:n.text+e})}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}
|
|
2408
2639
|
/**
|
|
2409
2640
|
* @license
|
|
2410
2641
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2411
2642
|
* SPDX-License-Identifier: MIT
|
|
2412
|
-
*/var
|
|
2643
|
+
*/var Ot=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class It{constructor(t,e,n,i,o){this.stateHandler=t,this.eventBus=e,this.ui=n,this.config=i,this.provider=o}setProvider(t){this.provider=t}createThread(t){return Ot(this,void 0,void 0,function*(){if(!this.config.enableThreads)throw new Error("Threads are not enabled");const e=this.stateHandler.getState(),n={id:this.generateId("thread"),title:t||`Chat ${e.threads.length+1}`,messages:[],createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString()};if(this.provider&&"function"==typeof this.provider.createConversation)try{const t=yield this.provider.createConversation(n.title);t&&t.id&&(n.id=String(t.id),n.conversationId=t.id)}catch(t){console.error("Error calling provider.createConversation:",t)}return this.stateHandler.updateState({threads:[n,...e.threads],currentThreadId:n.id,messages:[]}),this.eventBus.emit("thread:created",n),this.eventBus.emit("thread:selected",n),this.ui.focusInput&&setTimeout(()=>{this.ui.focusInput()},100),n})}switchThread(t){const e=this.stateHandler.getState(),n=e.threads.find(e=>e.id===t);if(!n)throw new Error(`Thread "${t}" not found`);e.currentThreadId&&this.saveCurrentThread(),this.stateHandler.updateState({currentThreadId:t,messages:[...n.messages]}),this.eventBus.emit("thread:selected",n)}bookmarkThread(t){const e=this.stateHandler.getState(),n=e.threads.find(e=>e.id===t);if(!n)throw new Error(`Thread "${t}" not found`);const i=!n.bookmarked,o=e.threads.map(e=>e.id===t?Object.assign(Object.assign({},e),{bookmarked:i}):e);this.stateHandler.updateState({threads:o}),this.eventBus.emit("thread:bookmarked",{threadId:t,bookmarked:i})}renameThread(t,e){const n=this.stateHandler.getState();if(!n.threads.find(e=>e.id===t))throw new Error(`Thread "${t}" not found`);const i=n.threads.map(n=>n.id===t?Object.assign(Object.assign({},n),{title:e,updatedAt:(new Date).toISOString()}):n);this.stateHandler.updateState({threads:i}),this.eventBus.emit("thread:renamed",{threadId:t,title:e})}deleteThread(t){const e=this.stateHandler.getState(),n=e.threads.filter(e=>e.id!==t);e.currentThreadId===t?n.length>0?(this.stateHandler.updateState({threads:n}),this.switchThread(n[0].id)):this.stateHandler.updateState({threads:n,currentThreadId:void 0,messages:[]}):this.stateHandler.updateState({threads:n}),this.eventBus.emit("thread:deleted",t)}getCurrentThread(){const t=this.stateHandler.getState();return t.threads.find(e=>e.id===t.currentThreadId)}getThreads(){return[...this.stateHandler.getState().threads]}saveCurrentThread(){const t=this.stateHandler.getState();t.currentThreadId&&this.updateThreadMessages(t.currentThreadId)}updateThreadMessages(t){const e=this.stateHandler.getState(),n=e.threads.map(n=>n.id===t?Object.assign(Object.assign({},n),{messages:[...e.messages],updatedAt:(new Date).toISOString()}):n);this.stateHandler.updateState({threads:n})}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}
|
|
2413
2644
|
/**
|
|
2414
2645
|
* @license
|
|
2415
2646
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2416
2647
|
* SPDX-License-Identifier: MIT
|
|
2417
|
-
*/var
|
|
2648
|
+
*/var Rt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class At{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)}removeFile(t){const e=this.stateHandler.getState();this.stateHandler.updateState({uploadedFiles:e.uploadedFiles.filter(e=>e.id!==t)}),this.eventBus.emit("file:removed",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 Rt(this,void 0,void 0,function*(){return{id:this.generateId("file"),name:t.name,size:t.size,type:this.determineFileType(t.type),mimeType:t.type,uploadProgress:100}})}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)}`}}
|
|
2418
2649
|
/**
|
|
2419
2650
|
* @license
|
|
2420
2651
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2421
2652
|
* SPDX-License-Identifier: MIT
|
|
2422
|
-
*/class
|
|
2653
|
+
*/class jt{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(),n=e.selectedModules.includes(t)?e.selectedModules.filter(e=>e!==t):[...e.selectedModules,t];this.selectModules(n)}getSelectedModules(){const t=this.stateHandler.getState();return(t.modules||[]).filter(e=>t.selectedModules.includes(e.id))}clearSelection(){this.stateHandler.updateState({selectedModules:[]})}}
|
|
2423
2654
|
/**
|
|
2424
2655
|
* @license
|
|
2425
2656
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2426
2657
|
* SPDX-License-Identifier: MIT
|
|
2427
|
-
*/class
|
|
2658
|
+
*/class Dt{constructor(t){this.stateHandler=t}setSuggestions(t){this.stateHandler.updateState({suggestions:t})}clearSuggestions(){this.stateHandler.updateState({suggestions:[]})}getSuggestions(){return[...this.stateHandler.getState().suggestions]}removeSuggestion(t){const e=this.stateHandler.getState();this.stateHandler.updateState({suggestions:e.suggestions.filter(e=>e.id!==t)})}}
|
|
2428
2659
|
/**
|
|
2429
2660
|
* @license
|
|
2430
2661
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2431
2662
|
* SPDX-License-Identifier: MIT
|
|
2432
|
-
*/var
|
|
2663
|
+
*/var Ft=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Nt{constructor(t,e,n,i,o,s,r){this.stateHandler=e,this.messageHandler=n,this.fileHandler=i,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 Ft(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(),n=this.provider.sendMessage(t.text,e);yield this.processStream(n)}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 Ft(this,void 0,void 0,function*(){var e;let n=null;const i=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)),o=[];let s="",r="",a=0;if(i.length>0)for(const t of i)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 c=yield t.next();if(l=c.done||!1,l||!c.value)break;const d=String(c.value),h=d.startsWith(r)?d.slice(r.length):d;r=d,s+=h;let u="",p=!1;for(;s.length;){const t=o[o.length-1];if(t){const e=t.buffer+s,i=e.indexOf(t.close);if(-1===i){t.buffer=e,s="";break}const r=e.slice(0,i),a="function"==typeof t.plugin.renderHtmlBlock?t.plugin.renderHtmlBlock(t.name,r):"";if(a)if(t.hasPlaceholder&&n){const t=/<div data-placeholder-id="[^"]*">[\s\S]*?<\/div>/;t.test(n.text)?(n.text=n.text.replace(t,a),this.messageHandler.updateMessage(n.id,{text:n.text})):(u+=a,p=!0)}else u+=a,p=!0;o.pop(),s=e.slice(i+t.close.length);continue}if(0===i.length){u+=s,s="";break}let e=null;for(const t of i)for(const n of t.htmlTags){const i=s.indexOf(n.open);-1!==i&&(!e||i<e.idx)&&(e={idx:i,plugin:t,name:n.name,open:n.open,close:n.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 n=e.plugin.renderHtmlBlockPlaceholder(e.name);n&&(u+=n,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);n?u&&(this.messageHandler.appendToBotMessage(n.id,u),n.text+=u,f&&!(null===(e=n.metadata)||void 0===e?void 0:e.renderAsHtml)&&this.messageHandler.updateMessage(n.id,{metadata:Object.assign(Object.assign({},n.metadata||{}),{renderAsHtml:!0})})):(n=this.messageHandler.createBotMessage(u,f?{renderAsHtml:!0}:void 0),this.stateHandler.addMessageToState(n),this.ui.onTypingEnd&&this.ui.onTypingEnd(),this.stateHandler.setTyping(!1))}if(!this.cancelRequested&&n&&(s&&this.messageHandler.appendToBotMessage(n.id,s),o.length>0)){const t=o.map(t=>t.open+t.buffer).join("");t&&this.messageHandler.appendToBotMessage(n.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 Ft(this,void 0,void 0,function*(){var e,n;if(!(null===(n=null===(e=this.provider)||void 0===e?void 0:e.capabilities)||void 0===n?void 0:n.fileUpload)||!this.provider.uploadFile)throw new Error("Provider does not support file upload");const i=this.buildContext();return yield this.provider.uploadFile(t,i)})}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)}}
|
|
2433
2664
|
/**
|
|
2434
2665
|
* @license
|
|
2435
2666
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2436
2667
|
* SPDX-License-Identifier: MIT
|
|
2437
|
-
*/var
|
|
2668
|
+
*/var Bt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Lt{constructor(t){this.validators=[],this.validators=t.validators||[]}validateMessage(t){return Bt(this,void 0,void 0,function*(){const e=[],n=[];t.trim()||e.push("Message cannot be empty");for(const i of this.validators)try{(yield i.validator(t))||(e.push(i.errorMessage),i.warningMessage&&n.push(i.warningMessage))}catch(t){this.logError("Validation error:",t),e.push("Validation failed")}return{isValid:0===e.length,errors:e,warnings:n}})}validateFile(t,e){const n=[],i=(null==e?void 0:e.maxFileSize)||10485760;if(t.size>i&&n.push(`File size exceeds maximum allowed (${this.formatFileSize(i)})`),(null==e?void 0:e.allowedTypes)&&e.allowedTypes.length>0){e.allowedTypes.some(e=>e.startsWith(".")?t.name.toLowerCase().endsWith(e.toLowerCase()):t.type.includes(e))||n.push(`File type not allowed. Allowed types: ${e.allowedTypes.join(", ")}`)}return{isValid:0===n.length,errors:n,warnings:[]}}addValidator(t){this.validators.push(t)}removeValidator(t){this.validators=this.validators.filter(e=>e.id!==t)}clearValidators(){this.validators=[]}getValidators(){return[...this.validators]}formatFileSize(t){if(0===t)return"0 Bytes";const e=Math.floor(Math.log(t)/Math.log(1024));return Math.round(t/Math.pow(1024,e)*100)/100+" "+["Bytes","KB","MB","GB"][e]}logError(t,e){console.error(`[ValidationService] ${t}`,e)}}
|
|
2438
2669
|
/**
|
|
2439
2670
|
* @license
|
|
2440
2671
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2441
2672
|
* SPDX-License-Identifier: MIT
|
|
2442
|
-
*/var
|
|
2673
|
+
*/var Ut=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Wt{constructor(t,e,n){this.stateHandler=e,this.config=n,this.storage=t,this.setupAutoSave()}setStorage(t){this.storage=t,this.setupAutoSave()}saveState(){return Ut(this,arguments,void 0,function*(t="chatbot-state"){if(!this.storage)throw new Error("No storage configured");try{const e=this.stateHandler.getState();yield this.storage.save(t,e),this.log("State saved to storage")}catch(t){throw this.logError("Error saving to storage:",t),t}})}loadState(){return Ut(this,arguments,void 0,function*(t="chatbot-state"){if(!this.storage)throw new Error("No storage configured");try{const e=yield this.storage.load(t);e&&(this.stateHandler.updateState(e),this.log("State loaded from storage"))}catch(t){throw this.logError("Error loading from storage:",t),t}})}clearStorage(){return Ut(this,void 0,void 0,function*(){if(!this.storage)throw new Error("No storage configured");try{yield this.storage.clear(),this.log("Storage cleared")}catch(t){throw this.logError("Error clearing storage:",t),t}})}setupAutoSave(){this.autoSaveTimer&&clearInterval(this.autoSaveTimer),this.config.autoSaveInterval&&this.storage&&(this.autoSaveTimer=setInterval(()=>{this.saveState().catch(t=>{this.logError("Auto-save failed:",t)})},this.config.autoSaveInterval))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=void 0)}startAutoSave(t){this.config.autoSaveInterval=t,this.setupAutoSave()}hasStorage(){return!!this.storage}destroy(){this.stopAutoSave()}log(t){console.log(`[StorageService] ${t}`)}logError(t,e){console.error(`[StorageService] ${t}`,e)}}
|
|
2443
2674
|
/**
|
|
2444
2675
|
* @license
|
|
2445
2676
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2446
2677
|
* SPDX-License-Identifier: MIT
|
|
2447
|
-
*/var
|
|
2678
|
+
*/var Ht=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Jt{constructor(t){this.plugins=new Map,t&&t.forEach(t=>this.registerPlugin(t))}registerPlugin(t,e){if(this.plugins.has(t.id))this.log(`Plugin "${t.id}" is already registered, skipping`);else if(this.plugins.set(t.id,t),this.log(`Registered plugin: ${t.name} v${t.version}`),t.onInit&&e)try{t.onInit(e)}catch(e){this.logError(`Error initializing plugin "${t.id}":`,e)}}unregisterPlugin(t){const e=this.plugins.get(t);if(e&&e.onDestroy)try{e.onDestroy()}catch(e){this.logError(`Error destroying plugin "${t}":`,e)}this.plugins.delete(t),this.log(`Unregistered plugin: ${t}`)}getPlugin(t){return this.plugins.get(t)}getAllPlugins(){return Array.from(this.plugins.values())}hasPlugin(t){return this.plugins.has(t)}getPluginsMap(){return this.plugins}executeHook(t,...e){return Ht(this,void 0,void 0,function*(){for(const n of this.plugins.values()){const i=n[t];if("function"==typeof i)try{yield i(...e)}catch(e){this.logError(`Error executing hook "${String(t)}" on plugin "${n.id}":`,e)}}})}clearPlugins(){this.plugins.forEach((t,e)=>{this.unregisterPlugin(e)}),this.plugins.clear()}getPluginCount(){return this.plugins.size}log(t){console.log(`[PluginService] ${t}`)}logError(t,e){console.error(`[PluginService] ${t}`,e)}}const qt=["ar","fr"],Vt="__nuraly_localization__";!function(){if(globalThis[Vt])return globalThis[Vt];const t=R({sourceLocale:"en",targetLocales:qt,loadLocale:t=>import(`../../locales/generated/${t}.js`)});globalThis[Vt]=t}();
|
|
2448
2679
|
/**
|
|
2449
2680
|
* @license
|
|
2450
2681
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2451
2682
|
* SPDX-License-Identifier: MIT
|
|
2452
2683
|
*/
|
|
2453
|
-
var Wt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Ht{constructor(t={}){this.plugins=new Map,this.config=t,this.ui=t.ui||{},this.eventBus=new $t,this.pluginService=new Lt,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 St(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new Pt(this.stateHandler,this.eventBus,this.plugins),this.threadHandler=new Et(this.stateHandler,this.eventBus,this.ui,this.config,t.provider),this.fileHandler=new zt(this.stateHandler,this.eventBus),this.moduleHandler=new Ct(this.stateHandler,this.eventBus),this.suggestionHandler=new It(this.stateHandler),this.providerService=new Rt(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new At(this.config),this.storageService=new Ft(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Wt(this,void 0,void 0,function*(){try{t.isConnected()||(yield t.connect({})),yield this.autoLoadConversations(t)}catch(t){this.logError("Failed to connect provider:",t)}})}initializeState(t){const e=t.initialMessages?t.initialMessages.map(t=>this.processMessageThroughPlugins(t)):[];return{messages:e,threads:t.initialThreads||[],modules:t.enableModules?[]:void 0,selectedModules:[],uploadedFiles:[],suggestions:t.initialSuggestions||[],isTyping:!1,isProcessing:!1,currentThreadId:void 0,metadata:t.metadata||{}}}processMessageThroughPlugins(t){if(!t.text||"string"!=typeof t.text)return t;const e=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)&&t.htmlTags.length>0);if(0===e.length)return t;let n=t.text,i=!1;for(const t of e){const e=t.htmlTags;for(const o of e){const e=o.open,s=o.close;let r=0;for(;;){const a=n.indexOf(e,r);if(-1===a)break;const l=a+e.length,d=n.indexOf(s,l);if(-1===d){r=l;continue}const c=n.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?(n=n.substring(0,a)+h+n.substring(d+s.length),i=!0,r=a+h.length):r=d+s.length}}}return i?Object.assign(Object.assign({},t),{text:n,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0})}):t}processRestoredMessagesForPlugins(){const t=this.stateHandler.getState();if(t.messages&&0!==t.messages.length)for(const e of t.messages)"bot"===e.sender&&this.plugins.forEach(t=>{if(t.onMessageReceived)try{t.onMessageReceived(e)}catch(t){}})}setupLifecycleHooks(){this.onBeforeInit(),this.onReady().catch(t=>{this.logError("Error during initialization:",t)})}onBeforeInit(){this.log("Initializing chatbot controller...")}onReady(){return Wt(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 Wt(this,arguments,void 0,function*(t,e={}){this.log("Sending message:",t);try{const n=this.stateHandler.getState();this.config.enableThreads&&!n.currentThreadId&&(yield this.threadHandler.createThread("New Chat"));const i=yield this.beforeMessageSent(t,e);if(!e.skipValidation){const t=yield this.validationService.validateMessage(i);if(!t.isValid){const e=new kt(t.errors);throw this.handleValidationError(e),e}}const o=this.messageHandler.createUserMessage(i,e.metadata);e.files&&(o.files=e.files),this.messageHandler.addMessage(o);const s=this.stateHandler.getState();return(e.threadId||s.currentThreadId)&&this.threadHandler.updateThreadMessages(e.threadId||s.currentThreadId),yield this.afterMessageSent(o),this.providerService.processMessage(o).catch(t=>{this.logError("Error processing with provider:",t)}),o}catch(t){throw this.handleError(t),t}})}stop(){this.providerService.stopCurrentProcessing()}addMessage(t){const e=this.messageHandler.createMessage(t),n="bot"===e.sender?this.processMessageThroughPlugins(e):e;return this.messageHandler.addMessage(n),n}updateMessage(t,e){this.messageHandler.updateMessage(t,e)}deleteMessage(t){this.messageHandler.deleteMessage(t)}clearMessages(){this.updateState({messages:[]})}getMessages(){return this.stateHandler.getState().messages}uploadFiles(t){return Wt(this,void 0,void 0,function*(){if(!this.config.enableFileUpload)throw new Error("File upload is not enabled");let e=t;if(!e&&this.ui.openFileDialog&&(e=yield this.ui.openFileDialog()),!e||0===e.length)return[];const n=[];for(const t of e)try{const e=yield this.validationService.validateFile(t,{maxFileSize:this.config.maxFileSize,allowedTypes:this.config.allowedFileTypes});if(!e.isValid){this.ui.showNotification&&this.ui.showNotification(e.errors[0]||"File validation failed","error");continue}const i=yield this.fileHandler.createChatbotFile(t),o=yield this.providerService.uploadFileToProvider(t);o&&Object.assign(i,o),n.push(i),this.fileHandler.addFile(i),this.ui.showFilePreview&&this.ui.showFilePreview(i)}catch(e){this.logError("Error uploading file:",e),this.ui.showNotification&&this.ui.showNotification(`Failed to upload ${t.name}`,"error")}return n})}removeFile(t){this.fileHandler.removeFile(t)}clearFiles(){this.fileHandler.clearFiles()}getUploadedFiles(){return this.stateHandler.getState().uploadedFiles}createThread(t){return Wt(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 Wt(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 Wt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Wt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Wt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Wt(this,void 0,void 0,function*(){this.logError("Provider error:",t);const e=this.messageHandler.createMessage({sender:J.Bot,text:"Sorry, there was an error processing your request.",state:K.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(()=>Wt(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 Wt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Wt(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 Wt(this,void 0,void 0,function*(){if(t&&"function"==typeof t.loadConversations)try{this.log("Auto-loading conversations from provider...");const e=yield t.loadConversations();if(Array.isArray(e)&&e.length>0){this.log(`Loaded ${e.length} conversation summaries`);const n=[];if("function"==typeof t.loadConversation)for(const i of e)try{const e=yield t.loadConversation(i.id);if(e){const t={id:e.id,title:e.title,messages:e.messages||[],createdAt:e.createdAt,updatedAt:e.updatedAt};n.push(t)}}catch(t){this.logError(`Failed to load conversation ${i.id}:`,t)}else for(const t of e){const e={id:t.id,title:t.title,messages:[],createdAt:t.createdAt,updatedAt:t.updatedAt};n.push(e)}n.length>0&&(this.log(`Successfully loaded ${n.length} conversations`),this.loadConversations(n))}else this.log("No conversations to load from provider")}catch(t){this.logError("Failed to auto-load conversations from provider:",t)}})}setUICallbacks(t){this.ui=Object.assign(Object.assign({},this.ui),t)}getConfig(){return Object.freeze(Object.assign({},this.config))}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t)}setTyping(t){this.updateState({isTyping:t}),this.emit(t?"typing:start":"typing:end")}setStatusText(t){this.updateState({statusText:t})}clearStatusText(){this.updateState({statusText:void 0})}getContext(){const t=this.stateHandler.getState();return{messages:t.messages,currentThread:this.getCurrentThread(),selectedModules:t.selectedModules,metadata:t.metadata,uploadedFiles:t.uploadedFiles}}destroy(){this.onDestroy()}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}formatFileSize(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}log(...t){this.config.debug&&console.log("[ChatbotCore]",...t)}logError(...t){console.error("[ChatbotCore]",...t)}}
|
|
2684
|
+
var Gt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Kt{constructor(t={}){this.plugins=new Map,this.config=t,this.ui=t.ui||{},this.eventBus=new Tt,this.pluginService=new Jt,this.plugins=this.pluginService.getPluginsMap(),t.plugins&&t.plugins.forEach(t=>this.pluginService.registerPlugin(t,this));const e=this.initializeState(t);if(this.stateHandler=new Ct(e,this.eventBus,this.ui,this.plugins,this.config),this.messageHandler=new zt(this.stateHandler,this.eventBus,this.plugins),this.threadHandler=new It(this.stateHandler,this.eventBus,this.ui,this.config,t.provider),this.fileHandler=new At(this.stateHandler,this.eventBus),this.moduleHandler=new jt(this.stateHandler,this.eventBus),this.suggestionHandler=new Dt(this.stateHandler),this.providerService=new Nt(t.provider,this.stateHandler,this.messageHandler,this.fileHandler,this.eventBus,this.ui,this.plugins),this.validationService=new Lt(this.config),this.storageService=new Wt(t.storage,this.stateHandler,this.config),t.provider){const e=t.provider;queueMicrotask(()=>{this.initializeProvider(e)})}this.setupLifecycleHooks()}initializeProvider(t){return Gt(this,void 0,void 0,function*(){try{t.isConnected()||(yield t.connect({})),yield this.autoLoadConversations(t)}catch(t){this.logError("Failed to connect provider:",t)}})}initializeState(t){const e=t.initialMessages?t.initialMessages.map(t=>this.processMessageThroughPlugins(t)):[];return{messages:e,threads:t.initialThreads||[],modules:t.enableModules?[]:void 0,selectedModules:[],uploadedFiles:[],suggestions:t.initialSuggestions||[],isTyping:!1,isProcessing:!1,currentThreadId:void 0,metadata:t.metadata||{}}}processMessageThroughPlugins(t){if(!t.text||"string"!=typeof t.text)return t;const e=Array.from(this.plugins.values()).filter(t=>Array.isArray(t.htmlTags)&&t.htmlTags.length>0);if(0===e.length)return t;let n=t.text,i=!1;for(const t of e){const e=t.htmlTags;for(const o of e){const e=o.open,s=o.close;let r=0;for(;;){const a=n.indexOf(e,r);if(-1===a)break;const l=a+e.length,c=n.indexOf(s,l);if(-1===c){r=l;continue}const d=n.substring(l,c);let h="";if("function"==typeof t.renderHtmlBlock)try{h=t.renderHtmlBlock(o.name,d)}catch(e){console.error(`[ChatbotCore] Error rendering HTML block for plugin ${t.id}:`,e)}h?(n=n.substring(0,a)+h+n.substring(c+s.length),i=!0,r=a+h.length):r=c+s.length}}}return i?Object.assign(Object.assign({},t),{text:n,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0})}):t}processRestoredMessagesForPlugins(){const t=this.stateHandler.getState();if(t.messages&&0!==t.messages.length)for(const e of t.messages)"bot"===e.sender&&this.plugins.forEach(t=>{if(t.onMessageReceived)try{t.onMessageReceived(e)}catch(t){}})}setupLifecycleHooks(){this.onBeforeInit(),this.onReady().catch(t=>{this.logError("Error during initialization:",t)})}onBeforeInit(){this.log("Initializing chatbot controller...")}onReady(){return Gt(this,void 0,void 0,function*(){this.log("Chatbot controller ready");try{const t=this.stateHandler.getState(),e=t.messages&&t.messages.length>0?t.messages[0]:void 0;e&&"bot"===e.sender&&e.introduction&&Array.isArray(e.suggestions)&&e.suggestions.length>0&&this.suggestionHandler.setSuggestions(e.suggestions)}catch(t){this.logError("Error initializing suggestions from initial messages:",t)}this.processRestoredMessagesForPlugins(),this.ui.onStateChange&&this.ui.onStateChange(this.getState()),this.emit("ready",this.stateHandler.getState())})}onDestroy(){this.log("Destroying chatbot controller..."),this.storageService.stopAutoSave(),this.pluginService.clearPlugins(),this.eventBus.removeAllListeners()}updateState(t){this.stateHandler.updateState(t)}sendMessage(t){return Gt(this,arguments,void 0,function*(t,e={}){this.log("Sending message:",t);try{const n=this.stateHandler.getState();this.config.enableThreads&&!n.currentThreadId&&(yield this.threadHandler.createThread("New Chat"));const i=yield this.beforeMessageSent(t,e);if(!e.skipValidation){const t=yield this.validationService.validateMessage(i);if(!t.isValid){const e=new Et(t.errors);throw this.handleValidationError(e),e}}const o=this.messageHandler.createUserMessage(i,e.metadata);e.files&&(o.files=e.files),this.messageHandler.addMessage(o);const s=this.stateHandler.getState();return(e.threadId||s.currentThreadId)&&this.threadHandler.updateThreadMessages(e.threadId||s.currentThreadId),yield this.afterMessageSent(o),this.providerService.processMessage(o).catch(t=>{this.logError("Error processing with provider:",t)}),o}catch(t){throw this.handleError(t),t}})}stop(){this.providerService.stopCurrentProcessing()}addMessage(t){const e=this.messageHandler.createMessage(t),n="bot"===e.sender?this.processMessageThroughPlugins(e):e;return this.messageHandler.addMessage(n),n}updateMessage(t,e){this.messageHandler.updateMessage(t,e)}deleteMessage(t){this.messageHandler.deleteMessage(t)}clearMessages(){this.updateState({messages:[]})}getMessages(){return this.stateHandler.getState().messages}uploadFiles(t){return Gt(this,void 0,void 0,function*(){if(!this.config.enableFileUpload)throw new Error("File upload is not enabled");let e=t;if(!e&&this.ui.openFileDialog&&(e=yield this.ui.openFileDialog()),!e||0===e.length)return[];const n=[];for(const t of e)try{const e=yield this.validationService.validateFile(t,{maxFileSize:this.config.maxFileSize,allowedTypes:this.config.allowedFileTypes});if(!e.isValid){this.ui.showNotification&&this.ui.showNotification(e.errors[0]||"File validation failed","error");continue}const i=yield this.fileHandler.createChatbotFile(t),o=yield this.providerService.uploadFileToProvider(t);o&&Object.assign(i,o),n.push(i),this.fileHandler.addFile(i),this.ui.showFilePreview&&this.ui.showFilePreview(i)}catch(e){this.logError("Error uploading file:",e),this.ui.showNotification&&this.ui.showNotification(`Failed to upload ${t.name}`,"error")}return n})}removeFile(t){this.fileHandler.removeFile(t)}clearFiles(){this.fileHandler.clearFiles()}getUploadedFiles(){return this.stateHandler.getState().uploadedFiles}createThread(t){return Gt(this,void 0,void 0,function*(){return yield this.threadHandler.createThread(t)})}switchThread(t){this.threadHandler.switchThread(t),this.processRestoredMessagesForPlugins()}deleteThread(t){this.threadHandler.deleteThread(t)}renameThread(t,e){this.threadHandler.renameThread(t,e)}bookmarkThread(t){this.threadHandler.bookmarkThread(t)}getCurrentThread(){const t=this.stateHandler.getState();return t.threads.find(e=>e.id===t.currentThreadId)}getThreads(){return this.stateHandler.getState().threads}setModules(t){this.moduleHandler.setModules(t)}selectModules(t){this.moduleHandler.selectModules(t)}toggleModule(t){this.moduleHandler.toggleModule(t)}getSelectedModules(){return this.moduleHandler.getSelectedModules()}setSuggestions(t){this.suggestionHandler.setSuggestions(t)}clearSuggestions(){this.suggestionHandler.clearSuggestions()}beforeMessageSent(t,e){return Gt(this,void 0,void 0,function*(){let e=t;for(const t of this.plugins.values())t.beforeSend&&(e=yield t.beforeSend(e));return e})}afterMessageSent(t){return Gt(this,void 0,void 0,function*(){this.log("Message sent:",t)})}beforeProviderCall(t){return Gt(this,void 0,void 0,function*(){this.log("Calling provider for message:",t.id)})}afterProviderCall(){return Gt(this,void 0,void 0,function*(){this.log("Provider call completed")})}handleProviderError(t){return Gt(this,void 0,void 0,function*(){this.logError("Provider error:",t);const e=this.messageHandler.createMessage({sender:q.Bot,text:"Sorry, there was an error processing your request.",state:Y.Error,timestamp:(new Date).toISOString()});this.messageHandler.addMessage(e),this.ui.showNotification&&this.ui.showNotification("Failed to process message","error"),this.emit("provider:error",t),yield this.pluginService.executeHook("onError",t)})}handleValidationError(t){this.logError("Validation error:",t),this.ui.showNotification&&this.ui.showNotification(t.errors[0],"error"),this.emit("validation:error",t)}handleError(t){this.logError("Error:",t),this.emit("error",t),this.plugins.forEach(e=>{e.onError&&e.onError(t)})}registerPlugin(t){this.pluginService.registerPlugin(t,this)}unregisterPlugin(t){this.pluginService.unregisterPlugin(t)}getPlugin(t){return this.pluginService.getPlugin(t)}setProvider(t){this.providerService.setProvider(t),t.isConnected()?(this.autoLoadConversations(t).catch(t=>{this.logError("Failed to auto-load conversations:",t)}),this.emit("provider:connected",t.id)):t.connect({}).then(()=>Gt(this,void 0,void 0,function*(){yield this.autoLoadConversations(t),this.emit("provider:connected",t.id)})).catch(t=>{this.logError("Failed to connect provider:",t)})}setStorage(t){this.storageService.setStorage(t)}saveToStorage(){return Gt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.saveState(t)})}loadFromStorage(){return Gt(this,arguments,void 0,function*(t="chatbot-state"){yield this.storageService.loadState(t);const e=this.stateHandler.getState();if(e.messages&&e.messages.length>0){const t=e.messages.map(t=>this.processMessageThroughPlugins(t));this.stateHandler.updateState({messages:t}),this.processRestoredMessagesForPlugins()}})}on(t,e){return this.eventBus.on(t,e)}emit(t,e){this.eventBus.emit(t,e)}getState(){return this.stateHandler.getState()}setState(t){t.messages&&Array.isArray(t.messages)&&(t.messages=t.messages.map(t=>this.processMessageThroughPlugins(t))),t.threads&&Array.isArray(t.threads)&&(t.threads=t.threads.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}))),this.updateState(t),t.messages&&this.processRestoredMessagesForPlugins()}loadConversations(t){const e=t.map(t=>Object.assign(Object.assign({},t),{messages:t.messages.map(t=>this.processMessageThroughPlugins(t))}));this.updateState({threads:e,currentThreadId:e.length>0?e[0].id:void 0,messages:e.length>0?e[0].messages:[]}),this.processRestoredMessagesForPlugins()}autoLoadConversations(t){return Gt(this,void 0,void 0,function*(){if(t&&"function"==typeof t.loadConversations)try{this.log("Auto-loading conversations from provider...");const e=yield t.loadConversations();if(Array.isArray(e)&&e.length>0){this.log(`Loaded ${e.length} conversation summaries`);const n=[];if("function"==typeof t.loadConversation)for(const i of e)try{const e=yield t.loadConversation(i.id);if(e){const t={id:e.id,title:e.title,messages:e.messages||[],createdAt:e.createdAt,updatedAt:e.updatedAt};n.push(t)}}catch(t){this.logError(`Failed to load conversation ${i.id}:`,t)}else for(const t of e){const e={id:t.id,title:t.title,messages:[],createdAt:t.createdAt,updatedAt:t.updatedAt};n.push(e)}n.length>0&&(this.log(`Successfully loaded ${n.length} conversations`),this.loadConversations(n))}else this.log("No conversations to load from provider")}catch(t){this.logError("Failed to auto-load conversations from provider:",t)}})}setUICallbacks(t){this.ui=Object.assign(Object.assign({},this.ui),t)}getConfig(){return Object.freeze(Object.assign({},this.config))}updateConfig(t){this.config=Object.assign(Object.assign({},this.config),t)}setTyping(t){this.updateState({isTyping:t}),this.emit(t?"typing:start":"typing:end")}setStatusText(t){this.updateState({statusText:t})}clearStatusText(){this.updateState({statusText:void 0})}getContext(){const t=this.stateHandler.getState();return{messages:t.messages,currentThread:this.getCurrentThread(),selectedModules:t.selectedModules,metadata:t.metadata,uploadedFiles:t.uploadedFiles}}destroy(){this.onDestroy()}generateId(t){return`${t}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}formatFileSize(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}log(...t){this.config.debug&&console.log("[ChatbotCore]",...t)}logError(...t){console.error("[ChatbotCore]",...t)}}
|
|
2454
2685
|
/**
|
|
2455
2686
|
* @license
|
|
2456
2687
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2457
2688
|
* SPDX-License-Identifier: MIT
|
|
2458
|
-
*/var
|
|
2689
|
+
*/var Yt=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},Xt=function(t){return this instanceof Xt?(this.v=t,this):new Xt(t)},Qt=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof Xt?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class Zt{constructor(){this.id="openai",this.name="OpenAI",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!0,imageGeneration:!0},this.apiKey="",this.apiUrl="https://api.openai.com/v1",this.model="gpt-4",this.temperature=.7,this.connected=!1}connect(t){return Yt(this,void 0,void 0,function*(){var e;if(!t.apiKey)throw new Error("OpenAI API key is required");this.apiKey=t.apiKey,this.apiUrl=t.apiUrl||this.apiUrl,this.model=t.model||this.model,this.temperature=null!==(e=t.temperature)&&void 0!==e?e:this.temperature,this.maxTokens=t.maxTokens;try{const t=yield fetch(`${this.apiUrl}/models`,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!t.ok)throw new Error(`OpenAI connection failed: ${t.statusText}`);this.connected=!0,console.log("[OpenAIProvider] Connected successfully")}catch(t){throw this.connected=!1,t}})}disconnect(){return Yt(this,void 0,void 0,function*(){this.connected=!1,console.log("[OpenAIProvider] Disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return Qt(this,arguments,function*(){var n,i,o;if(!this.connected)throw new Error("Provider not connected");const s=this.buildMessages(t,e),r=yield Xt(fetch(`${this.apiUrl}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:s,temperature:this.temperature,max_tokens:this.maxTokens,stream:!0})}));if(!r.ok)throw new Error(`OpenAI API error: ${r.statusText}`);if(!r.body)throw new Error("Response body is null");const a=r.body.getReader(),l=new TextDecoder;let c="";try{for(;;){const{done:t,value:e}=yield Xt(a.read());if(t)break;c+=l.decode(e,{stream:!0});const s=c.split("\n");c=s.pop()||"";for(const t of s)if(""!==t.trim()&&"data: [DONE]"!==t.trim()&&t.startsWith("data: ")){const e=t.slice(6);try{const t=null===(o=null===(i=null===(n=JSON.parse(e).choices)||void 0===n?void 0:n[0])||void 0===i?void 0:i.delta)||void 0===o?void 0:o.content;t&&(yield yield Xt(t))}catch(t){console.error("Error parsing SSE data:",t)}}}}finally{a.releaseLock()}})}getAvailableModules(){return Yt(this,void 0,void 0,function*(){return[{id:"web-search",name:"Web Search",description:"Search the web for information",icon:"search",enabled:!0},{id:"code-interpreter",name:"Code Interpreter",description:"Execute Python code",icon:"code",enabled:!0},{id:"dalle",name:"DALL-E",description:"Generate images",icon:"image",enabled:!0}]})}callModule(t,e){return Yt(this,void 0,void 0,function*(){return console.log(`[OpenAIProvider] Calling module: ${t}`,e),{success:!0,result:"Module executed"}})}uploadFile(t){return Yt(this,void 0,void 0,function*(){const e=new FormData;e.append("file",t),e.append("purpose","assistants");const n=yield fetch(`${this.apiUrl}/files`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:e});if(!n.ok)throw new Error(`File upload failed: ${n.statusText}`);const i=yield n.json();return{id:i.id,name:t.name,size:t.size,type:this.determineFileType(t.type),mimeType:t.type,url:i.url}})}onError(t){console.error("[OpenAIProvider] Error:",t)}buildMessages(t,e){const n=[],i=e.messages.slice(-10);for(const t of i)n.push({role:"user"===t.sender?"user":"assistant",content:t.text});return n.find(e=>"user"===e.role&&e.content===t)||n.push({role:"user",content:t}),n}determineFileType(t){return t.startsWith("image/")?"image":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":"document"}}
|
|
2459
2690
|
/**
|
|
2460
2691
|
* @license
|
|
2461
2692
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2462
2693
|
* SPDX-License-Identifier: MIT
|
|
2463
|
-
*/var
|
|
2694
|
+
*/var te=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},ee=function(t){return this instanceof ee?(this.v=t,this):new ee(t)},ne=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof ee?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class ie{constructor(){this.id="custom-api",this.name="Custom API",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.apiUrl="",this.headers={},this.connected=!1}connect(t){return te(this,void 0,void 0,function*(){if(!t.apiUrl)throw new Error("API URL is required");this.apiUrl=t.apiUrl,this.headers=Object.assign({},t.headers),this.headers["Content-Type"]||(this.headers["Content-Type"]="application/json"),t.apiKey&&(this.headers.Authorization=`Bearer ${t.apiKey}`),this.connected=!0,console.log("[CustomAPIProvider] Connected")})}disconnect(){return te(this,void 0,void 0,function*(){this.connected=!1,console.log("[CustomAPIProvider] Disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return ne(this,arguments,function*(){var n;if(!this.connected)return yield yield ee(this.formatError("Provider not connected","Please check your connection settings.")),yield ee(void 0);try{const i=this.buildPayload(t,e);let o,s;if(!(null===(n=this.headers["Content-Type"])||void 0===n?void 0:n.includes("multipart/form-data"))||"object"!=typeof i||i instanceof FormData)i instanceof FormData?(o=i,s=Object.assign({},this.headers),delete s["Content-Type"]):(o=JSON.stringify(i),s=this.headers);else{const t=new FormData;for(const[e,n]of Object.entries(i))null!=n&&t.append(e,"object"==typeof n?JSON.stringify(n):String(n));o=t,s=Object.assign({},this.headers),delete s["Content-Type"]}const r=yield ee(fetch(this.apiUrl,{method:"POST",headers:s,body:o}));if(!r.ok){const t=yield ee(r.text().catch(()=>r.statusText));return yield yield ee(this.formatError(`${r.status} ${r.statusText}`,t||"The server returned an error. Please try again.")),yield ee(void 0)}if(!r.body)return yield yield ee(this.formatError("Response Error","The server response body is empty.")),yield ee(void 0);const a=r.headers.get("content-type");if((null==a?void 0:a.includes("text/event-stream"))||(null==a?void 0:a.includes("stream"))||(null==a?void 0:a.includes("text/plain"))){const t=this.handleStreamResponse(r);let e=yield ee(t.next());for(;!e.done;)yield yield ee(e.value),e=yield ee(t.next())}else try{const t=yield ee(r.json());yield yield ee(this.extractMessage(t))}catch(t){yield yield ee(this.formatError("Parse Error","Failed to parse the server response."))}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ee(this.formatError("Network Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}handleStreamResponse(t){return ne(this,arguments,function*(){const e=t.body.getReader(),n=new TextDecoder;let i="";try{for(;;){const{done:t,value:o}=yield ee(e.read());if(t)break;i+=n.decode(o,{stream:!0}),yield yield ee(i)}i.length>0&&(yield yield ee(i))}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ee("\n\n"+this.formatError("Streaming Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}finally{e.releaseLock()}})}buildPayload(t,e){return{userMessage:t,variables:e.metadata||{},stream:!0}}extractMessage(t){return t.message||t.text||t.response||JSON.stringify(t)}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[CustomAPIProvider] Error:",t)}}
|
|
2464
2695
|
/**
|
|
2465
2696
|
* @license
|
|
2466
2697
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2467
2698
|
* SPDX-License-Identifier: MIT
|
|
2468
|
-
*/var
|
|
2699
|
+
*/var oe=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},se=function(t){return this instanceof se?(this.v=t,this):new se(t)},re=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,n=t[Symbol.asyncIterator];return n?n.call(t):(t="function"==typeof __values?__values(t):t[Symbol.iterator](),e={},i("next"),i("throw"),i("return"),e[Symbol.asyncIterator]=function(){return this},e);function i(n){e[n]=t[n]&&function(e){return new Promise(function(i,o){(function(t,e,n,i){Promise.resolve(i).then(function(e){t({value:e,done:n})},e)})(i,o,(e=t[n](e)).done,e.value)})}}},ae=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof se?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const le=["That's an interesting question! Let me think about that...","I understand what you're asking. Here's what I think:","Great point! Based on what you've told me, I would suggest:","I'd be happy to help with that. Let me explain:","That's a common question. The answer is:","I see where you're coming from. Let me clarify:","Excellent question! Here's my perspective:","I can definitely help you with that. Consider this:"],ce={hello:["Hello! 👋 How can I help you today?","Hi there! What can I do for you?","Hey! Great to see you. What's on your mind?"],help:["I'm here to help! You can ask me anything. Try asking about features, getting started, or technical questions.","I can assist with various topics. What do you need help with?","Sure! I'm ready to help. What would you like to know?"],bye:["Goodbye! Feel free to come back anytime! 👋","See you later! Have a great day!","Bye! It was nice chatting with you!"],thanks:["You're welcome! Happy to help! 😊","Glad I could help!","Anytime! That's what I'm here for!"],how:["Great question! Here's how it works: First, you need to understand the basics. Then, you can dive deeper into the specifics.","Let me explain the process step by step...","That's actually quite straightforward. Let me break it down for you:"],what:["Good question! Let me explain what that means...","That refers to a concept that's important to understand. Here's the breakdown:","Interesting topic! Here's what you need to know:"],why:["That's because of several factors. Let me explain the reasoning:","Great question! The main reason is that it provides better functionality and user experience.","There are multiple reasons for this. The primary one is:"]};class de{constructor(t={}){var e,n,i,o,s,r,a,l,c,d,h,u;this.id="mock-provider",this.name="Mock Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!1,functions:!0},this.messageCount=0,this.connected=!1,this.config={delay:null!==(e=t.delay)&&void 0!==e?e:800,streaming:null!==(n=t.streaming)&&void 0!==n&&n,streamingSpeed:null!==(i=t.streamingSpeed)&&void 0!==i?i:3,streamingInterval:null!==(o=t.streamingInterval)&&void 0!==o?o:50,contextualResponses:null===(s=t.contextualResponses)||void 0===s||s,echoMode:null!==(r=t.echoMode)&&void 0!==r&&r,customResponses:null!==(a=t.customResponses)&&void 0!==a?a:[],errorRate:null!==(l=t.errorRate)&&void 0!==l?l:0,useHistory:null===(c=t.useHistory)||void 0===c||c,simulateToolCalls:null!==(d=t.simulateToolCalls)&&void 0!==d&&d,toolCallNames:null!==(h=t.toolCallNames)&&void 0!==h?h:["search_web","get_weather","run_code"],toolCallDelay:null!==(u=t.toolCallDelay)&&void 0!==u?u:1500}}connect(t){return oe(this,void 0,void 0,function*(){yield this.delay(100),this.connected=!0,console.log("🤖 Mock Provider connected")})}disconnect(){return oe(this,void 0,void 0,function*(){this.connected=!1,console.log("🤖 Mock Provider disconnected")})}isConnected(){return this.connected}sendMessage(t,e){return ae(this,arguments,function*(){var n,i,o,s,r,a;if(this.messageCount++,Math.random()<this.config.errorRate)throw yield se(this.delay(this.config.delay/2)),new Error("Simulated API error for testing");if(yield se(this.delay(this.config.delay)),this.config.simulateToolCalls){const t=this.config.toolCallNames,e=1+Math.floor(Math.random()*Math.min(t.length,3));for(let n=0;n<e;n++){const e=t[n%t.length];null===(r=this.onToolCall)||void 0===r||r.call(this,e),yield se(this.delay(this.config.toolCallDelay)),null===(a=this.onToolCallEnd)||void 0===a||a.call(this)}}const l=this.generateResponse(t,e);if(this.config.streaming)try{for(var c,d=!0,h=re(this.streamResponse(l));!(n=(c=yield se(h.next())).done);d=!0){s=c.value,d=!1;const t=s;yield yield se(t)}}catch(t){i={error:t}}finally{try{d||n||!(o=h.return)||(yield se(o.call(h)))}finally{if(i)throw i.error}}else yield yield se(l)})}uploadFile(t){return oe(this,void 0,void 0,function*(){if(yield this.delay(this.config.delay),Math.random()<this.config.errorRate)throw new Error("Simulated file upload error for testing");const e=t.type||"application/octet-stream",n=this.determineFileType(e),i=`mock-file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;console.log(`📎 Mock Provider: File uploaded - ${t.name} (${t.size} bytes) - ID: ${i}`);return{id:i,name:t.name,size:t.size,type:n,mimeType:e,url:URL.createObjectURL(t),previewUrl:"image"===n?URL.createObjectURL(t):void 0,uploadProgress:100,metadata:{provider:"mock",uploadedAt:(new Date).toISOString()}}})}determineFileType(t){return t.startsWith("image/")?X.Image:t.startsWith("video/")?X.Video:t.startsWith("audio/")?X.Audio:t.startsWith("application/pdf")||t.includes("document")||t.includes("text")?X.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?X.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?X.Code:X.Unknown}generateResponse(t,e){var n,i;const o=(null==e?void 0:e.messages)||[],s=null===(n=[...o].map((t,e)=>({m:t,i:e})).reverse().find(({m:t})=>"user"===t.sender&&!!t.text))||void 0===n?void 0:n.i,r="number"==typeof s&&(null===(i=o[s])||void 0===i?void 0:i.text)?o[s].text:t;if(this.config.echoMode)return`You said: "${r}"`;if(this.config.customResponses.length>0){const t=(this.messageCount-1)%this.config.customResponses.length;return this.config.customResponses[t]}if(this.config.contextualResponses){const t=this.getContextualResponse(r);if(t)return t}if(this.config.useHistory&&o.length>0&&"number"==typeof s){const t=[...o].slice(0,s).reverse().find(t=>"user"===t.sender&&!!t.text);return t&&t.text?`Great point about "${String(r).substring(0,60)}". Considering your earlier message about "${String(t.text).substring(0,30)}...", ${this.getRandomResponse()}`:`Regarding "${String(r).substring(0,60)}", ${this.getRandomResponse()}`}return`Regarding "${String(r).substring(0,60)}", ${this.getRandomResponse()}`}getContextualResponse(t){const e=t.toLowerCase();for(const[t,n]of Object.entries(ce))if(e.includes(t)){return n[Math.floor(Math.random()*n.length)]}return null}getRandomResponse(){const t=Math.floor(Math.random()*le.length);return le[t]}streamResponse(t){return ae(this,arguments,function*(){let e="";const n=t.split(" ");for(let t=0;t<n.length;t++){e+=(t>0?" ":"")+n[t],yield yield se(e),t<n.length-1&&(yield se(this.delay(this.config.streamingInterval)))}})}delay(t){return new Promise(e=>setTimeout(e,t))}reset(){this.messageCount=0}updateConfig(t){Object.assign(this.config,t)}getConfig(){return Object.assign({},this.config)}}const he={fast:()=>new de({delay:300,streaming:!1,contextualResponses:!0}),realistic:()=>new de({delay:1200,streaming:!0,streamingInterval:50,contextualResponses:!0,useHistory:!0}),slow:()=>new de({delay:3e3,streaming:!1}),echo:()=>new de({delay:500,echoMode:!0}),streaming:()=>new de({delay:800,streaming:!0,streamingSpeed:2,streamingInterval:30}),unreliable:()=>new de({delay:1e3,errorRate:.3}),custom:t=>new de({delay:800,customResponses:t})};
|
|
2469
2700
|
/**
|
|
2470
2701
|
* @license
|
|
2471
2702
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2472
2703
|
* SPDX-License-Identifier: MIT
|
|
2473
|
-
*/var
|
|
2704
|
+
*/var ue=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},pe=function(t){return this instanceof pe?(this.v=t,this):new pe(t)},fe=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof pe?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const ge={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",toolCall:"tool:call",toolCallEnd:"tool:end"};class me{constructor(){this.id="socket",this.name="Socket.io Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.responseResolvers=new Map}connect(t){return ue(this,void 0,void 0,function*(){var e,n,i;if(!t.url)throw new Error("Socket URL is required");this.config=Object.assign(Object.assign({},t),{events:Object.assign(Object.assign({},ge),t.events),autoReconnect:null===(e=t.autoReconnect)||void 0===e||e,reconnectionAttempts:null!==(n=t.reconnectionAttempts)&&void 0!==n?n:5,responseTimeout:null!==(i=t.responseTimeout)&&void 0!==i?i:3e4});const o=t.namespace?`${t.url}${t.namespace}`:t.url;return this.socket=h(o,{path:t.path||"/socket.io",transports:["websocket","polling"],autoConnect:!0,reconnection:this.config.autoReconnect,reconnectionAttempts:this.config.reconnectionAttempts,extraHeaders:t.headers}),new Promise((t,e)=>{const n=setTimeout(()=>{e(new Error("Socket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(n),this.connected=!0,console.log("[SocketProvider] Connected:",this.socket.id),t()}),this.socket.on("connect_error",t=>{clearTimeout(n),console.error("[SocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[SocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}setupEventListeners(){if(!this.socket||!this.config)return;const t=this.config.events;this.socket.on(t.response,t=>{console.log("[SocketProvider] Response received:",t);const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=this.extractMessage(t);n.resolve(i),this.responseResolvers.delete(e)}}),t.stream&&this.socket.on(t.stream,t=>{console.log("[SocketProvider] Stream chunk:",t);const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){n.isStreaming=!0;const e=this.extractMessage(t);n.chunks.push(e)}}),t.error&&this.socket.on(t.error,t=>{console.error("[SocketProvider] Error event:",t);const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=t.error||t.message||"Unknown error";n.reject(new Error(i)),this.responseResolvers.delete(e)}}),t.toolCall&&this.socket.on(t.toolCall,t=>{var e;const n=t.name||t.toolName||t.function||"unknown";null===(e=this.onToolCall)||void 0===e||e.call(this,n)}),t.toolCallEnd&&this.socket.on(t.toolCallEnd,()=>{var t;null===(t=this.onToolCallEnd)||void 0===t||t.call(this)})}getLatestResolver(){const t=Array.from(this.responseResolvers.keys());return t.length>0?this.responseResolvers.get(t[t.length-1]):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessage(t){var e,n,i;return(null===(e=this.config)||void 0===e?void 0:e.extractMessage)?this.config.extractMessage(t):"string"==typeof t?t:t.message?t.message:t.text?t.text:t.response?t.response:t.content?t.content:(null===(n=t.data)||void 0===n?void 0:n.message)?t.data.message:(null===(i=t.data)||void 0===i?void 0:i.output)?JSON.stringify(t.data.output):JSON.stringify(t)}disconnect(){return ue(this,void 0,void 0,function*(){this.socket&&(this.socket.disconnect(),this.socket=null),this.connected=!1,this.responseResolvers.clear(),console.log("[SocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return fe(this,arguments,function*(){if(!this.connected||!this.socket||!this.config)return yield yield pe(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield pe(void 0);const n=`msg_${Date.now()}_${crypto.randomUUID().slice(0,9)}`,i=this.buildPayload(t,e,n);try{const t=new Promise((t,e)=>{this.responseResolvers.set(n,{resolve:t,reject:e,chunks:[],isStreaming:!1}),setTimeout(()=>{const i=this.responseResolvers.get(n);i&&(i.chunks.length>0?t(i.chunks.join("")):e(new Error("Response timeout")),this.responseResolvers.delete(n))},this.config.responseTimeout)});if(console.log("[SocketProvider] Sending message:",this.config.events.send,i),this.socket.emit(this.config.events.send,i),this.config.events.stream){const e=this.responseResolvers.get(n);let i=0;const o=setInterval(()=>{e&&e.chunks.length>i&&(i=e.chunks.length)},50);try{const e=yield pe(t);clearInterval(o),yield yield pe(e)}catch(t){throw clearInterval(o),t}}else{const e=yield pe(t);yield yield pe(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield pe(this.formatError("Socket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildPayload(t,e,n){var i,o,s;if(null===(i=this.config)||void 0===i?void 0:i.buildPayload){const i=this.config.buildPayload(t,e);return Object.assign(Object.assign({},i),{messageId:n})}return{messageId:n,message:t,text:t,threadId:null===(o=e.currentThread)||void 0===o?void 0:o.id,modules:e.selectedModules,metadata:e.metadata,files:null===(s=e.uploadedFiles)||void 0===s?void 0:s.map(t=>({id:t.id,name:t.name,type:t.type,url:t.url}))}}emit(t,e){this.socket&&this.connected&&this.socket.emit(t,e)}on(t,e){this.socket&&this.socket.on(t,e)}off(t,e){this.socket&&this.socket.off(t,e)}getSocket(){return this.socket}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[SocketProvider] Error:",t)}}
|
|
2474
2705
|
/**
|
|
2475
2706
|
* @license
|
|
2476
2707
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2477
2708
|
* SPDX-License-Identifier: MIT
|
|
2478
|
-
*/var ue=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},pe=function(t){return this instanceof pe?(this.v=t,this):new pe(t)},fe=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof pe?Promise.resolve(n.value.v).then(l,d):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}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 ge{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 ue(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/socket`;return this.socket=c(e,{path:this.config.socketPath,query:{l:JSON.stringify({workflowId:this.config.workflowId})},transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const n=setTimeout(()=>{e(new Error("Socket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(n),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(n),console.error("[WorkflowSocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[WorkflowSocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}subscribeToWorkflow(t){this.socket&&(this.socket.emit("nk:subscribe:workflow",{workflowId:t}),console.log("[WorkflowSocketProvider] Subscribed to workflow:",t))}subscribeToExecution(t){this.socket&&(this.socket.emit("nk:subscribe:execution",{executionId:t}),console.log("[WorkflowSocketProvider] Subscribed to execution:",t))}setupEventListeners(){this.socket&&(this.socket.onAny((t,...e)=>{console.log("[WorkflowSocketProvider] RAW event:",t,e[0])}),this.socket.on("nk:data",t=>{(null==t?void 0:t.event)&&t.data&&this._handleEvent(t.event,t.data)}),this.socket.on("execution:chat-message",t=>this._handleEvent("execution:chat-message",t)),this.socket.on("execution:started",t=>this._handleEvent("execution:started",t)),this.socket.on("execution:completed",t=>this._handleEvent("execution:completed",t)),this.socket.on("execution:failed",t=>this._handleEvent("execution:failed",t)),this.socket.on("execution:node-started",t=>this._handleEvent("execution:node-started",t)),this.socket.on("execution:node-completed",t=>this._handleEvent("execution:node-completed",t)))}_handleEvent(t,e){var n,i,o,s,r;switch(t){case"execution:chat-message":{const t=e.executionId,o=e.message;if(console.log("[WorkflowSocketProvider] Chat message received:",t,o),!t||!o)return;const s=this.activeExecutions.get(t);if(!s)return void(null===(i=null===(n=this.config)||void 0===n?void 0:n.onMessage)||void 0===i||i.call(n,o));s.completed||s.messages.push(o);break}case"execution:started":console.log("[WorkflowSocketProvider] Execution started (event):",e.executionId);break;case"execution:completed":{const t=e.executionId;if(console.log("[WorkflowSocketProvider] Execution completed:",t),!t)return;const n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0;let i="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)i=this.config.extractResponse(e);else if(n.messages.length>0)i=n.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;i=t.response||t.message||t.result||JSON.stringify(t)}catch(t){i=e.outputData}n.resolve(i||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,n=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,n),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0,i.reject(new Error(n)),this.activeExecutions.delete(t);break}case"execution:node-started":console.log("[WorkflowSocketProvider] Node started:",e.nodeName),e.nodeName&&(null===(s=this.onNodeStarted)||void 0===s||s.call(this,e.nodeName));break;case"execution:node-completed":console.log("[WorkflowSocketProvider] Node completed:",e.nodeName),e.nodeName&&(null===(r=this.onNodeCompleted)||void 0===r||r.call(this,e.nodeName))}}disconnect(){return ue(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 fe(this,arguments,function*(){var n,i;if(!this.connected||!this.socket||!this.config)return yield yield pe(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield pe(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 pe(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield pe(a.text().catch(()=>a.statusText));return yield yield pe(this.formatError(`${a.status} ${a.statusText}`,t)),yield pe(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(n=yield pe(a.json().catch(()=>({}))))||void 0===n?void 0:n.executionId);if(!l)return yield yield pe(this.formatError("Execution Error","No execution ID received from server")),yield pe(void 0);console.log("[WorkflowSocketProvider] Execution started:",l),(null===(i=this.config)||void 0===i?void 0:i.onExecutionStart)&&this.config.onExecutionStart(l,this.config.workflowId),this.subscribeToExecution(l);const d=new Promise((t,e)=>{this.activeExecutions.set(l,{messages:[],resolve:t,reject:e,completed:!1}),setTimeout(()=>{const n=this.activeExecutions.get(l);n&&!n.completed&&(n.completed=!0,n.messages.length>0?t(n.messages.join("\n\n")):e(new Error("Execution timeout")),this.activeExecutions.delete(l))},this.config.responseTimeout)}),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 pe(t)}yield pe(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield pe(d);yield yield pe(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield pe(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var n,i,o;if(null===(n=this.config)||void 0===n?void 0:n.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(i=e.currentThread)||void 0===i?void 0:i.id)||this.sessionId,r={message:t,threadId:s,modules:e.selectedModules,metadata:e.metadata,files:(null===(o=e.uploadedFiles)||void 0===o?void 0:o.map(t=>{var e;return{id:t.id,name:t.name,type:t.type,mimeType:t.mimeType,url:t.url,base64:null===(e=t.metadata)||void 0===e?void 0:e.base64}}))||[]};return console.log("[WorkflowSocketProvider] buildInput threadId:",s,"files count:",r.files.length),r}setWorkflowId(t){this.config&&(this.socket&&this.config.workflowId&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.config.workflowId=t,this.socket&&this.connected&&this.subscribeToWorkflow(t))}getSocket(){return this.socket}uploadFile(t){return ue(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,n=URL.createObjectURL(t),i=yield this.fileToBase64(t),o=t.type||"application/octet-stream",s=this.determineFileType(o);return console.log(`[WorkflowSocketProvider] File prepared: ${t.name} (${t.size} bytes)`),{id:e,name:t.name,size:t.size,type:s,mimeType:o,url:n,previewUrl:s===Y.Image?n:void 0,uploadProgress:100,metadata:{provider:"workflow-socket",uploadedAt:(new Date).toISOString(),base64:i}}})}fileToBase64(t){return new Promise((e,n)=>{const i=new FileReader;i.onload=()=>{const t=i.result,n=t.split(",")[1]||t;e(n)},i.onerror=n,i.readAsDataURL(t)})}determineFileType(t){return t.startsWith("image/")?Y.Image:t.startsWith("video/")?Y.Video:t.startsWith("audio/")?Y.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?Y.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?Y.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?Y.Code:Y.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2709
|
+
*/var ve=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},be=function(t){return this instanceof be?(this.v=t,this):new be(t)},ye=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof be?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};class xe{constructor(){this.id="workflow-socket",this.name="Workflow Socket Provider",this.capabilities={streaming:!0,fileUpload:!0,modules:!0,functions:!1},this.socket=null,this.config=null,this.connected=!1,this.sessionId=`session_${Date.now()}_${Math.random().toString(36).substring(2,11)}`,this.activeExecutions=new Map}connect(t){return ve(this,void 0,void 0,function*(){if(!t.workflowId)throw new Error("Workflow ID is required");this.config=Object.assign({socketUrl:t.socketUrl||("undefined"!=typeof window?window.location.origin:"http://localhost:8000"),socketPath:t.socketPath||"/__nk_socketio/",triggerEndpoint:t.triggerEndpoint||"/api/v1/workflows/{workflowId}/trigger/chat",responseTimeout:t.responseTimeout||6e4},t);const e=`${this.config.socketUrl}/nk/apps/workflows/:workflowId`;return this.socket=h(e,{path:this.config.socketPath,query:{l:JSON.stringify({workflowId:this.config.workflowId})},transports:["websocket","polling"],autoConnect:!0,reconnection:!0,reconnectionAttempts:5}),new Promise((t,e)=>{const n=setTimeout(()=>{e(new Error("Socket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(n),this.connected=!0,console.log("[WorkflowSocketProvider] Connected:",this.socket.id),this.subscribeToWorkflow(this.config.workflowId),t()}),this.socket.on("connect_error",t=>{clearTimeout(n),console.error("[WorkflowSocketProvider] Connection error:",t),e(t)}),this.socket.on("disconnect",t=>{this.connected=!1,console.log("[WorkflowSocketProvider] Disconnected:",t)}),this.setupEventListeners()})})}subscribeToWorkflow(t){this.socket&&(this.socket.emit("nk:subscribe:workflow",{workflowId:t}),console.log("[WorkflowSocketProvider] Subscribed to workflow:",t))}subscribeToExecution(t){this.socket&&(this.socket.emit("nk:subscribe:execution",{executionId:t}),console.log("[WorkflowSocketProvider] Subscribed to execution:",t))}setupEventListeners(){this.socket&&(this.socket.onAny((t,...e)=>{console.log("[WorkflowSocketProvider] RAW event:",t,e[0])}),this.socket.on("nk:data",t=>{(null==t?void 0:t.event)&&t.data&&this._handleEvent(t.event,t.data)}),this.socket.on("execution:chat-message",t=>this._handleEvent("execution:chat-message",t)),this.socket.on("execution:started",t=>this._handleEvent("execution:started",t)),this.socket.on("execution:completed",t=>this._handleEvent("execution:completed",t)),this.socket.on("execution:failed",t=>this._handleEvent("execution:failed",t)),this.socket.on("execution:node-started",t=>this._handleEvent("execution:node-started",t)),this.socket.on("execution:node-completed",t=>this._handleEvent("execution:node-completed",t)))}_handleEvent(t,e){var n,i,o,s,r;switch(t){case"execution:chat-message":{const t=e.executionId,o=e.message;if(console.log("[WorkflowSocketProvider] Chat message received:",t,o),!t||!o)return;const s=this.activeExecutions.get(t);if(!s)return void(null===(i=null===(n=this.config)||void 0===n?void 0:n.onMessage)||void 0===i||i.call(n,o));s.completed||s.messages.push(o);break}case"execution:started":console.log("[WorkflowSocketProvider] Execution started (event):",e.executionId);break;case"execution:completed":{const t=e.executionId;if(console.log("[WorkflowSocketProvider] Execution completed:",t),!t)return;const n=this.activeExecutions.get(t);if(!n||n.completed)return;n.completed=!0;let i="";if(null===(o=this.config)||void 0===o?void 0:o.extractResponse)i=this.config.extractResponse(e);else if(n.messages.length>0)i=n.messages.join("\n\n");else if(e.outputData)try{const t="string"==typeof e.outputData?JSON.parse(e.outputData):e.outputData;i=t.response||t.message||t.result||JSON.stringify(t)}catch(t){i=e.outputData}n.resolve(i||"Workflow completed"),this.activeExecutions.delete(t);break}case"execution:failed":{const t=e.executionId,n=e.errorMessage||e.error||"Workflow execution failed";if(console.error("[WorkflowSocketProvider] Execution failed:",t,n),!t)return;const i=this.activeExecutions.get(t);if(!i||i.completed)return;i.completed=!0,i.reject(new Error(n)),this.activeExecutions.delete(t);break}case"execution:node-started":console.log("[WorkflowSocketProvider] Node started:",e.nodeName),e.nodeName&&(null===(s=this.onNodeStarted)||void 0===s||s.call(this,e.nodeName));break;case"execution:node-completed":console.log("[WorkflowSocketProvider] Node completed:",e.nodeName),e.nodeName&&(null===(r=this.onNodeCompleted)||void 0===r||r.call(this,e.nodeName))}}disconnect(){return ve(this,void 0,void 0,function*(){var t;this.socket&&((null===(t=this.config)||void 0===t?void 0:t.workflowId)&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.socket.disconnect(),this.socket=null),this.connected=!1,this.activeExecutions.clear(),console.log("[WorkflowSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&!0===(null===(t=this.socket)||void 0===t?void 0:t.connected)}sendMessage(t,e){return ye(this,arguments,function*(){var n,i;if(!this.connected||!this.socket||!this.config)return yield yield be(this.formatError("Not Connected","Socket is not connected. Please check your connection.")),yield be(void 0);try{const o=this.buildInput(t,e),s=this.config.triggerEndpoint.replace("{workflowId}",this.config.workflowId),r=`${this.config.socketUrl}${s}`;console.log("[WorkflowSocketProvider] Triggering workflow:",r,o);const a=yield be(fetch(r,{method:"POST",headers:Object.assign({"Content-Type":"application/json"},this.config.headers),body:JSON.stringify(o)}));if(!a.ok){const t=yield be(a.text().catch(()=>a.statusText));return yield yield be(this.formatError(`${a.status} ${a.statusText}`,t)),yield be(void 0)}const l=a.headers.get("X-Execution-Id")||(null===(n=yield be(a.json().catch(()=>({}))))||void 0===n?void 0:n.executionId);if(!l)return yield yield be(this.formatError("Execution Error","No execution ID received from server")),yield be(void 0);console.log("[WorkflowSocketProvider] Execution started:",l),(null===(i=this.config)||void 0===i?void 0:i.onExecutionStart)&&this.config.onExecutionStart(l,this.config.workflowId),this.subscribeToExecution(l);const c=new Promise((t,e)=>{this.activeExecutions.set(l,{messages:[],resolve:t,reject:e,completed:!1}),setTimeout(()=>{const n=this.activeExecutions.get(l);n&&!n.completed&&(n.completed=!0,n.messages.length>0?t(n.messages.join("\n\n")):e(new Error("Execution timeout")),this.activeExecutions.delete(l))},this.config.responseTimeout)}),d=this.activeExecutions.get(l);let h=0;const u=setInterval(()=>{d.messages.length>h&&(h=d.messages.length)},100);try{for(;!d.completed;){if(d.messages.length>0){const t=d.messages.join("\n\n");yield yield be(t)}yield be(new Promise(t=>setTimeout(t,200)))}clearInterval(u);const t=yield be(c);yield yield be(t)}catch(t){throw clearInterval(u),t}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield be(this.formatError("Workflow Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}buildInput(t,e){var n,i,o;if(null===(n=this.config)||void 0===n?void 0:n.buildInput)return this.config.buildInput(t,e);console.log("[WorkflowSocketProvider] buildInput context.uploadedFiles:",e.uploadedFiles);const s=(null===(i=e.currentThread)||void 0===i?void 0:i.id)||this.sessionId,r={message:t,threadId:s,modules:e.selectedModules,metadata:e.metadata,files:(null===(o=e.uploadedFiles)||void 0===o?void 0:o.map(t=>{var e;return{id:t.id,name:t.name,type:t.type,mimeType:t.mimeType,url:t.url,base64:null===(e=t.metadata)||void 0===e?void 0:e.base64}}))||[]};return console.log("[WorkflowSocketProvider] buildInput threadId:",s,"files count:",r.files.length),r}setWorkflowId(t){this.config&&(this.socket&&this.config.workflowId&&this.socket.emit("nk:unsubscribe:workflow",{workflowId:this.config.workflowId}),this.config.workflowId=t,this.socket&&this.connected&&this.subscribeToWorkflow(t))}getSocket(){return this.socket}uploadFile(t){return ve(this,void 0,void 0,function*(){const e=`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,n=URL.createObjectURL(t),i=yield this.fileToBase64(t),o=t.type||"application/octet-stream",s=this.determineFileType(o);return console.log(`[WorkflowSocketProvider] File prepared: ${t.name} (${t.size} bytes)`),{id:e,name:t.name,size:t.size,type:s,mimeType:o,url:n,previewUrl:s===X.Image?n:void 0,uploadProgress:100,metadata:{provider:"workflow-socket",uploadedAt:(new Date).toISOString(),base64:i}}})}fileToBase64(t){return new Promise((e,n)=>{const i=new FileReader;i.onload=()=>{const t=i.result,n=t.split(",")[1]||t;e(n)},i.onerror=n,i.readAsDataURL(t)})}determineFileType(t){return t.startsWith("image/")?X.Image:t.startsWith("video/")?X.Video:t.startsWith("audio/")?X.Audio:t.startsWith("application/pdf")||t.includes("document")||t.startsWith("text/")?X.Document:t.includes("zip")||t.includes("rar")||t.includes("tar")?X.Archive:t.includes("javascript")||t.includes("json")||t.includes("xml")?X.Code:X.Unknown}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[WorkflowSocketProvider] Error:",t)}}
|
|
2479
2710
|
/**
|
|
2480
2711
|
* @license
|
|
2481
2712
|
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2482
2713
|
* SPDX-License-Identifier: MIT
|
|
2483
|
-
*/var me=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},ve=function(t){return this instanceof ve?(this.v=t,this):new ve(t)},be=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,d)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof ve?Promise.resolve(n.value.v).then(l,d):c(s[0][2],n)}catch(t){c(s[0][3],t)}var n}function l(t){a("next",t)}function d(t){a("throw",t)}function c(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const ye={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",ping:"ping",pong:"pong",toolCall:"tool:call",toolCallEnd:"tool:end"};class xe{constructor(){this.id="native-websocket",this.name="Native WebSocket Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.ws=null,this.config=null,this.connected=!1,this.responseResolvers=new Map,this.reconnectAttempt=0,this.reconnectTimer=null,this.heartbeatTimer=null,this.pongTimer=null,this.intentionalClose=!1,this.messageListeners=new Map}connect(t){return me(this,void 0,void 0,function*(){var e,n,i,o,s,r,a,l,d,c;if(!t.url)throw new Error("WebSocket URL is required");return this.config=Object.assign(Object.assign({},t),{messageTypes:Object.assign(Object.assign({},ye),t.messageTypes),typeField:null!==(e=t.typeField)&&void 0!==e?e:"type",autoReconnect:null===(n=t.autoReconnect)||void 0===n||n,maxReconnectAttempts:null!==(i=t.maxReconnectAttempts)&&void 0!==i?i:5,reconnectBaseDelay:null!==(o=t.reconnectBaseDelay)&&void 0!==o?o:1e3,reconnectMaxDelay:null!==(s=t.reconnectMaxDelay)&&void 0!==s?s:3e4,connectionTimeout:null!==(r=t.connectionTimeout)&&void 0!==r?r:1e4,responseTimeout:null!==(a=t.responseTimeout)&&void 0!==a?a:3e4,enableHeartbeat:null===(l=t.enableHeartbeat)||void 0===l||l,heartbeatInterval:null!==(d=t.heartbeatInterval)&&void 0!==d?d:3e4,heartbeatTimeout:null!==(c=t.heartbeatTimeout)&&void 0!==c?c:1e4}),this.intentionalClose=!1,this.reconnectAttempt=0,this.createConnection()})}createConnection(){return new Promise((t,e)=>{const n=this.config;if(!n)return void e(new Error("Provider not configured"));const i=this.buildUrl();try{this.ws=n.protocols?new WebSocket(i,n.protocols):new WebSocket(i)}catch(t){return void e(new Error(`Failed to create WebSocket: ${t instanceof Error?t.message:String(t)}`))}const o=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),e(new Error("WebSocket connection timeout")))},n.connectionTimeout);this.ws.onopen=()=>{var e,n;clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,console.log("[NativeWebSocketProvider] Connected"),null===(n=null===(e=this.config)||void 0===e?void 0:e.onConnectionChange)||void 0===n||n.call(e,!0),this.startHeartbeat(),t()},this.ws.onclose=t=>{var n,i;clearTimeout(o);const s=this.connected;this.connected=!1,this.stopHeartbeat(),console.log("[NativeWebSocketProvider] Disconnected:",t.code,t.reason),s&&(null===(i=null===(n=this.config)||void 0===n?void 0:n.onConnectionChange)||void 0===i||i.call(n,!1));for(const[t,e]of this.responseResolvers)e.chunks.length>0?e.resolve(e.chunks.join("")):e.reject(new Error("WebSocket connection closed")),this.responseResolvers.delete(t);!this.intentionalClose&&s?this.attemptReconnect():s||e(new Error(`WebSocket connection failed (code: ${t.code})`))},this.ws.onerror=t=>{console.error("[NativeWebSocketProvider] Error:",t)},this.ws.onmessage=t=>{this.handleMessage(t)}})}buildUrl(){const t=this.config;if(!t)return"";let e=t.url;const n=t.queryParams;if(n&&Object.keys(n).length>0){const t=e.includes("?")?"&":"?";e=`${e}${t}${Object.entries(n).map(([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&")}`}return e}handleMessage(t){var e,n,i;if(!this.config)return;const o=this.parseMessageData(t.data);if(!o)return;const s=o[null!==(e=this.config.typeField)&&void 0!==e?e:"type"],r=this.config.messageTypes;if(s!==r.pong)if(s!==r.ping){if(s===r.toolCall){const t=o.name||o.toolName||o.function||"unknown";return null===(n=this.onToolCall)||void 0===n||n.call(this,t),void this.dispatchToListeners(s,o)}if(s===r.toolCallEnd)return null===(i=this.onToolCallEnd)||void 0===i||i.call(this),void this.dispatchToListeners(s,o);this.dispatchToListeners(s,o),s!==r.response?s!==r.stream?s===r.error&&this.handleErrorMessage(o):this.handleStreamMessage(o):this.handleResponseMessage(o)}else this.send(r.pong,{timestamp:Date.now()});else this.handlePong()}parseMessageData(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return console.warn("[NativeWebSocketProvider] Non-JSON message received:",t),null}}dispatchToListeners(t,e){if(!t)return;const n=this.messageListeners.get(t);if(n)for(const t of n)try{t(e)}catch(t){console.error("[NativeWebSocketProvider] Listener error:",t)}}handleResponseMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=this.extractMessageContent(t);n.resolve(i),this.responseResolvers.delete(e)}}handleStreamMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){n.isStreaming=!0;const e=this.extractMessageContent(t);n.chunks.push(e)}}handleErrorMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=t.error||t.message||"Unknown error";n.reject(new Error(i)),this.responseResolvers.delete(e)}}getLatestResolver(){const t=Array.from(this.responseResolvers.keys()).at(-1);return void 0!==t?this.responseResolvers.get(t):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessageContent(t){var e,n,i;return(null===(e=this.config)||void 0===e?void 0:e.extractMessage)?this.config.extractMessage(t):"string"==typeof t?t:t.message?t.message:t.text?t.text:t.response?t.response:t.content?t.content:(null===(n=t.data)||void 0===n?void 0:n.message)?t.data.message:(null===(i=t.data)||void 0===i?void 0:i.output)?JSON.stringify(t.data.output):JSON.stringify(t)}startHeartbeat(){var t;if(!(null===(t=this.config)||void 0===t?void 0:t.enableHeartbeat))return;this.stopHeartbeat();const e=this.config.messageTypes;this.heartbeatTimer=setInterval(()=>{var t,n,i;this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN&&(this.send(e.ping,{timestamp:Date.now()}),this.pongTimer=setTimeout(()=>{var t;console.warn("[NativeWebSocketProvider] Heartbeat timeout — closing connection"),null===(t=this.ws)||void 0===t||t.close(4e3,"Heartbeat timeout")},null!==(i=null===(n=this.config)||void 0===n?void 0:n.heartbeatTimeout)&&void 0!==i?i:1e4))},this.config.heartbeatInterval)}handlePong(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}attemptReconnect(){var t,e,n,i,o,s;if(!(null===(t=this.config)||void 0===t?void 0:t.autoReconnect))return;const r=null!==(e=this.config.maxReconnectAttempts)&&void 0!==e?e:5;if(this.reconnectAttempt>=r)return void console.error("[NativeWebSocketProvider] Max reconnection attempts reached");this.reconnectAttempt++;const a=null!==(n=this.config.reconnectBaseDelay)&&void 0!==n?n:1e3,l=null!==(i=this.config.reconnectMaxDelay)&&void 0!==i?i:3e4,d=Math.min(a*Math.pow(2,this.reconnectAttempt-1)+Math.random()*a,l);console.log(`[NativeWebSocketProvider] Reconnecting in ${Math.round(d)}ms (attempt ${this.reconnectAttempt}/${r})`),null===(s=(o=this.config).onReconnectAttempt)||void 0===s||s.call(o,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>me(this,void 0,void 0,function*(){try{yield this.createConnection(),console.log("[NativeWebSocketProvider] Reconnected successfully")}catch(t){}}),d)}disconnect(){return me(this,void 0,void 0,function*(){this.intentionalClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.connected=!1,this.responseResolvers.clear(),this.messageListeners.clear(),console.log("[NativeWebSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN}sendMessage(t,e){return be(this,arguments,function*(){if(!this.connected||!this.ws||!this.config)return yield yield ve(this.formatError("Not Connected","WebSocket is not connected. Please check your connection.")),yield ve(void 0);const n=`msg_${Date.now()}_${crypto.randomUUID().slice(0,9)}`,i=this.buildPayload(t,e,n);try{const t=new Promise((t,e)=>{var i,o;this.responseResolvers.set(n,{resolve:t,reject:e,chunks:[],isStreaming:!1}),setTimeout(()=>{const i=this.responseResolvers.get(n);i&&(i.chunks.length>0?t(i.chunks.join("")):e(new Error("Response timeout")),this.responseResolvers.delete(n))},null!==(o=null===(i=this.config)||void 0===i?void 0:i.responseTimeout)&&void 0!==o?o:3e4)}),e=this.config.messageTypes;if(this.send(e.send,Object.assign(Object.assign({},i),{messageId:n})),this.config.messageTypes.stream){const e=this.responseResolvers.get(n);let i=0;const o=setInterval(()=>{e&&e.chunks.length>i&&(i=e.chunks.length)},50);try{const e=yield ve(t);clearInterval(o),yield yield ve(e)}catch(t){throw clearInterval(o),t}}else{const e=yield ve(t);yield yield ve(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield ve(this.formatError("WebSocket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}send(t,e){var n;if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.config){const i=null!==(n=this.config.typeField)&&void 0!==n?n:"type",o=Object.assign({[i]:t},e);this.ws.send(JSON.stringify(o))}}onMessage(t,e){var n;return this.messageListeners.has(t)||this.messageListeners.set(t,new Set),null===(n=this.messageListeners.get(t))||void 0===n||n.add(e),()=>{const n=this.messageListeners.get(t);n&&(n.delete(e),0===n.size&&this.messageListeners.delete(t))}}getWebSocket(){return this.ws}buildPayload(t,e,n){var i,o,s;if(null===(i=this.config)||void 0===i?void 0:i.buildPayload){const i=this.config.buildPayload(t,e);return Object.assign(Object.assign({},i),{messageId:n})}return{messageId:n,message:t,text:t,threadId:null===(o=e.currentThread)||void 0===o?void 0:o.id,modules:e.selectedModules,metadata:e.metadata,files:null===(s=e.uploadedFiles)||void 0===s?void 0:s.map(t=>({id:t.id,name:t.name,type:t.type,url:t.url}))}}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[NativeWebSocketProvider] Error:",t)}}
|
|
2714
|
+
*/var we=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})},_e=function(t){return this instanceof _e?(this.v=t,this):new _e(t)},$e=function(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,o=n.apply(t,e||[]),s=[];return i=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),r("next"),r("throw"),r("return",function(t){return function(e){return Promise.resolve(e).then(t,c)}}),i[Symbol.asyncIterator]=function(){return this},i;function r(t,e){o[t]&&(i[t]=function(e){return new Promise(function(n,i){s.push([t,e,n,i])>1||a(t,e)})},e&&(i[t]=e(i[t])))}function a(t,e){try{(n=o[t](e)).value instanceof _e?Promise.resolve(n.value.v).then(l,c):d(s[0][2],n)}catch(t){d(s[0][3],t)}var n}function l(t){a("next",t)}function c(t){a("throw",t)}function d(t,e){t(e),s.shift(),s.length&&a(s[0][0],s[0][1])}};const ke={send:"message:send",response:"message:response",stream:"message:stream",error:"message:error",typingStart:"typing:start",typingEnd:"typing:end",ping:"ping",pong:"pong",toolCall:"tool:call",toolCallEnd:"tool:end"};class Se{constructor(){this.id="native-websocket",this.name="Native WebSocket Provider",this.capabilities={streaming:!0,fileUpload:!1,modules:!1,functions:!1},this.ws=null,this.config=null,this.connected=!1,this.responseResolvers=new Map,this.reconnectAttempt=0,this.reconnectTimer=null,this.heartbeatTimer=null,this.pongTimer=null,this.intentionalClose=!1,this.messageListeners=new Map}connect(t){return we(this,void 0,void 0,function*(){var e,n,i,o,s,r,a,l,c,d;if(!t.url)throw new Error("WebSocket URL is required");return this.config=Object.assign(Object.assign({},t),{messageTypes:Object.assign(Object.assign({},ke),t.messageTypes),typeField:null!==(e=t.typeField)&&void 0!==e?e:"type",autoReconnect:null===(n=t.autoReconnect)||void 0===n||n,maxReconnectAttempts:null!==(i=t.maxReconnectAttempts)&&void 0!==i?i:5,reconnectBaseDelay:null!==(o=t.reconnectBaseDelay)&&void 0!==o?o:1e3,reconnectMaxDelay:null!==(s=t.reconnectMaxDelay)&&void 0!==s?s:3e4,connectionTimeout:null!==(r=t.connectionTimeout)&&void 0!==r?r:1e4,responseTimeout:null!==(a=t.responseTimeout)&&void 0!==a?a:3e4,enableHeartbeat:null===(l=t.enableHeartbeat)||void 0===l||l,heartbeatInterval:null!==(c=t.heartbeatInterval)&&void 0!==c?c:3e4,heartbeatTimeout:null!==(d=t.heartbeatTimeout)&&void 0!==d?d:1e4}),this.intentionalClose=!1,this.reconnectAttempt=0,this.createConnection()})}createConnection(){return new Promise((t,e)=>{const n=this.config;if(!n)return void e(new Error("Provider not configured"));const i=this.buildUrl();try{this.ws=n.protocols?new WebSocket(i,n.protocols):new WebSocket(i)}catch(t){return void e(new Error(`Failed to create WebSocket: ${t instanceof Error?t.message:String(t)}`))}const o=setTimeout(()=>{this.ws&&this.ws.readyState!==WebSocket.OPEN&&(this.ws.close(),e(new Error("WebSocket connection timeout")))},n.connectionTimeout);this.ws.onopen=()=>{var e,n;clearTimeout(o),this.connected=!0,this.reconnectAttempt=0,console.log("[NativeWebSocketProvider] Connected"),null===(n=null===(e=this.config)||void 0===e?void 0:e.onConnectionChange)||void 0===n||n.call(e,!0),this.startHeartbeat(),t()},this.ws.onclose=t=>{var n,i;clearTimeout(o);const s=this.connected;this.connected=!1,this.stopHeartbeat(),console.log("[NativeWebSocketProvider] Disconnected:",t.code,t.reason),s&&(null===(i=null===(n=this.config)||void 0===n?void 0:n.onConnectionChange)||void 0===i||i.call(n,!1));for(const[t,e]of this.responseResolvers)e.chunks.length>0?e.resolve(e.chunks.join("")):e.reject(new Error("WebSocket connection closed")),this.responseResolvers.delete(t);!this.intentionalClose&&s?this.attemptReconnect():s||e(new Error(`WebSocket connection failed (code: ${t.code})`))},this.ws.onerror=t=>{console.error("[NativeWebSocketProvider] Error:",t)},this.ws.onmessage=t=>{this.handleMessage(t)}})}buildUrl(){const t=this.config;if(!t)return"";let e=t.url;const n=t.queryParams;if(n&&Object.keys(n).length>0){const t=e.includes("?")?"&":"?";e=`${e}${t}${Object.entries(n).map(([t,e])=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&")}`}return e}handleMessage(t){var e,n,i;if(!this.config)return;const o=this.parseMessageData(t.data);if(!o)return;const s=o[null!==(e=this.config.typeField)&&void 0!==e?e:"type"],r=this.config.messageTypes;if(s!==r.pong)if(s!==r.ping){if(s===r.toolCall){const t=o.name||o.toolName||o.function||"unknown";return null===(n=this.onToolCall)||void 0===n||n.call(this,t),void this.dispatchToListeners(s,o)}if(s===r.toolCallEnd)return null===(i=this.onToolCallEnd)||void 0===i||i.call(this),void this.dispatchToListeners(s,o);this.dispatchToListeners(s,o),s!==r.response?s!==r.stream?s===r.error&&this.handleErrorMessage(o):this.handleStreamMessage(o):this.handleResponseMessage(o)}else this.send(r.pong,{timestamp:Date.now()});else this.handlePong()}parseMessageData(t){try{return"string"==typeof t?JSON.parse(t):t}catch(e){return console.warn("[NativeWebSocketProvider] Non-JSON message received:",t),null}}dispatchToListeners(t,e){if(!t)return;const n=this.messageListeners.get(t);if(n)for(const t of n)try{t(e)}catch(t){console.error("[NativeWebSocketProvider] Listener error:",t)}}handleResponseMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=this.extractMessageContent(t);n.resolve(i),this.responseResolvers.delete(e)}}handleStreamMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){n.isStreaming=!0;const e=this.extractMessageContent(t);n.chunks.push(e)}}handleErrorMessage(t){const e=this.extractMessageId(t),n=this.responseResolvers.get(e)||this.getLatestResolver();if(n){const i=t.error||t.message||"Unknown error";n.reject(new Error(i)),this.responseResolvers.delete(e)}}getLatestResolver(){const t=Array.from(this.responseResolvers.keys()).at(-1);return void 0!==t?this.responseResolvers.get(t):null}extractMessageId(t){return t.messageId||t.id||t.executionId||"default"}extractMessageContent(t){var e,n,i;return(null===(e=this.config)||void 0===e?void 0:e.extractMessage)?this.config.extractMessage(t):"string"==typeof t?t:t.message?t.message:t.text?t.text:t.response?t.response:t.content?t.content:(null===(n=t.data)||void 0===n?void 0:n.message)?t.data.message:(null===(i=t.data)||void 0===i?void 0:i.output)?JSON.stringify(t.data.output):JSON.stringify(t)}startHeartbeat(){var t;if(!(null===(t=this.config)||void 0===t?void 0:t.enableHeartbeat))return;this.stopHeartbeat();const e=this.config.messageTypes;this.heartbeatTimer=setInterval(()=>{var t,n,i;this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN&&(this.send(e.ping,{timestamp:Date.now()}),this.pongTimer=setTimeout(()=>{var t;console.warn("[NativeWebSocketProvider] Heartbeat timeout — closing connection"),null===(t=this.ws)||void 0===t||t.close(4e3,"Heartbeat timeout")},null!==(i=null===(n=this.config)||void 0===n?void 0:n.heartbeatTimeout)&&void 0!==i?i:1e4))},this.config.heartbeatInterval)}handlePong(){this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.pongTimer&&(clearTimeout(this.pongTimer),this.pongTimer=null)}attemptReconnect(){var t,e,n,i,o,s;if(!(null===(t=this.config)||void 0===t?void 0:t.autoReconnect))return;const r=null!==(e=this.config.maxReconnectAttempts)&&void 0!==e?e:5;if(this.reconnectAttempt>=r)return void console.error("[NativeWebSocketProvider] Max reconnection attempts reached");this.reconnectAttempt++;const a=null!==(n=this.config.reconnectBaseDelay)&&void 0!==n?n:1e3,l=null!==(i=this.config.reconnectMaxDelay)&&void 0!==i?i:3e4,c=Math.min(a*Math.pow(2,this.reconnectAttempt-1)+Math.random()*a,l);console.log(`[NativeWebSocketProvider] Reconnecting in ${Math.round(c)}ms (attempt ${this.reconnectAttempt}/${r})`),null===(s=(o=this.config).onReconnectAttempt)||void 0===s||s.call(o,this.reconnectAttempt,r),this.reconnectTimer=setTimeout(()=>we(this,void 0,void 0,function*(){try{yield this.createConnection(),console.log("[NativeWebSocketProvider] Reconnected successfully")}catch(t){}}),c)}disconnect(){return we(this,void 0,void 0,function*(){this.intentionalClose=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.stopHeartbeat(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.connected=!1,this.responseResolvers.clear(),this.messageListeners.clear(),console.log("[NativeWebSocketProvider] Disconnected")})}isConnected(){var t;return this.connected&&(null===(t=this.ws)||void 0===t?void 0:t.readyState)===WebSocket.OPEN}sendMessage(t,e){return $e(this,arguments,function*(){if(!this.connected||!this.ws||!this.config)return yield yield _e(this.formatError("Not Connected","WebSocket is not connected. Please check your connection.")),yield _e(void 0);const n=`msg_${Date.now()}_${crypto.randomUUID().slice(0,9)}`,i=this.buildPayload(t,e,n);try{const t=new Promise((t,e)=>{var i,o;this.responseResolvers.set(n,{resolve:t,reject:e,chunks:[],isStreaming:!1}),setTimeout(()=>{const i=this.responseResolvers.get(n);i&&(i.chunks.length>0?t(i.chunks.join("")):e(new Error("Response timeout")),this.responseResolvers.delete(n))},null!==(o=null===(i=this.config)||void 0===i?void 0:i.responseTimeout)&&void 0!==o?o:3e4)}),e=this.config.messageTypes;if(this.send(e.send,Object.assign(Object.assign({},i),{messageId:n})),this.config.messageTypes.stream){const e=this.responseResolvers.get(n);let i=0;const o=setInterval(()=>{e&&e.chunks.length>i&&(i=e.chunks.length)},50);try{const e=yield _e(t);clearInterval(o),yield yield _e(e)}catch(t){throw clearInterval(o),t}}else{const e=yield _e(t);yield yield _e(e)}}catch(t){const e=t instanceof Error?t.message:String(t);yield yield _e(this.formatError("WebSocket Error",e)),this.onError(t instanceof Error?t:new Error(String(t)))}})}send(t,e){var n;if(this.ws&&this.ws.readyState===WebSocket.OPEN&&this.config){const i=null!==(n=this.config.typeField)&&void 0!==n?n:"type",o=Object.assign({[i]:t},e);this.ws.send(JSON.stringify(o))}}onMessage(t,e){var n;return this.messageListeners.has(t)||this.messageListeners.set(t,new Set),null===(n=this.messageListeners.get(t))||void 0===n||n.add(e),()=>{const n=this.messageListeners.get(t);n&&(n.delete(e),0===n.size&&this.messageListeners.delete(t))}}getWebSocket(){return this.ws}buildPayload(t,e,n){var i,o,s;if(null===(i=this.config)||void 0===i?void 0:i.buildPayload){const i=this.config.buildPayload(t,e);return Object.assign(Object.assign({},i),{messageId:n})}return{messageId:n,message:t,text:t,threadId:null===(o=e.currentThread)||void 0===o?void 0:o.id,modules:e.selectedModules,metadata:e.metadata,files:null===(s=e.uploadedFiles)||void 0===s?void 0:s.map(t=>({id:t.id,name:t.name,type:t.type,url:t.url}))}}formatError(t,e){return`[ERROR_START][ERROR_TITLE_START]${t}[ERROR_TITLE_END]${e}[ERROR_END]`}onError(t){console.error("[NativeWebSocketProvider] Error:",t)}}
|
|
2484
2715
|
/**
|
|
2485
2716
|
* @license
|
|
2486
2717
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2487
2718
|
* SPDX-License-Identifier: MIT
|
|
2488
|
-
*/var
|
|
2719
|
+
*/var Pe=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Me{constructor(t,e={}){this.id="persistence",this.name="Persistence Plugin",this.version="1.0.0",this.storage=t,this.storageKey=e.storageKey||"chatbot-state",e.autoSaveInterval&&(this.autoSaveInterval=setInterval(()=>{this.saveState()},e.autoSaveInterval))}onInit(t){this.controller=t,this.loadState(),console.log("[PersistencePlugin] Initialized")}onDestroy(){this.autoSaveInterval&&clearInterval(this.autoSaveInterval),this.saveState(),console.log("[PersistencePlugin] Destroyed")}onStateChange(){this.saveState()}saveState(){return Pe(this,void 0,void 0,function*(){if(this.controller)try{const t=this.controller.getState();yield this.storage.save(this.storageKey,t),console.log("[PersistencePlugin] State saved")}catch(t){console.error("[PersistencePlugin] Error saving state:",t)}})}loadState(){return Pe(this,void 0,void 0,function*(){if(this.controller)try{const t=yield this.storage.load(this.storageKey);t&&(this.controller.setState(t),console.log("[PersistencePlugin] State loaded"))}catch(t){console.error("[PersistencePlugin] Error loading state:",t)}})}clearStorage(){return Pe(this,void 0,void 0,function*(){try{yield this.storage.remove(this.storageKey),console.log("[PersistencePlugin] Storage cleared")}catch(t){console.error("[PersistencePlugin] Error clearing storage:",t)}})}}
|
|
2489
2720
|
/**
|
|
2490
2721
|
* @license
|
|
2491
2722
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2492
2723
|
* SPDX-License-Identifier: MIT
|
|
2493
|
-
*/class
|
|
2724
|
+
*/class Te{constructor(t){this.id="analytics",this.name="Analytics Plugin",this.version="1.0.0",this.trackEvent=t}onInit(){this.trackEvent("chatbot:initialized",{timestamp:(new Date).toISOString()}),console.log("[AnalyticsPlugin] Initialized")}onDestroy(){this.trackEvent("chatbot:destroyed",{timestamp:(new Date).toISOString()}),console.log("[AnalyticsPlugin] Destroyed")}onMessageSent(t){this.trackEvent("chatbot:message:sent",{messageId:t.id,messageLength:t.text.length,hasFiles:!!t.files&&t.files.length>0,timestamp:t.timestamp})}onMessageReceived(t){this.trackEvent("chatbot:message:received",{messageId:t.id,messageLength:t.text.length,sender:t.sender,timestamp:t.timestamp})}onError(t){this.trackEvent("chatbot:error",{error:t.message,stack:t.stack,timestamp:(new Date).toISOString()})}}
|
|
2494
2725
|
/**
|
|
2495
2726
|
* @license
|
|
2496
2727
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2497
2728
|
* SPDX-License-Identifier: MIT
|
|
2498
|
-
*/class
|
|
2729
|
+
*/class Ee{constructor(){this._stylesInjected=!1}getOncePerConversationStyleTag(t,e="nr-chatbot"){var n;const i=`data-plugin-styles-${this.id}`;let o=!1;try{const t=document.querySelector(e);o=!!(null===(n=null==t?void 0:t.shadowRoot)||void 0===n?void 0:n.querySelector(`style[${i}]`))}catch(t){}return this._stylesInjected||o?"":(this._stylesInjected=!0,`<style ${i}="true">${t}</style>`)}onStateChange(t){try{const e=null==t?void 0:t.currentThreadId;e!==this._lastThreadId&&(this._lastThreadId=e,this._stylesInjected=!1)}catch(t){}}}
|
|
2499
2730
|
/**
|
|
2500
2731
|
* @license
|
|
2501
2732
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2502
2733
|
* SPDX-License-Identifier: MIT
|
|
2503
|
-
*/var
|
|
2734
|
+
*/var Ce=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class ze extends Ee{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 n=this.getStyles();return`${this.getOncePerConversationStyleTag(n)}${dt(e)}`}afterReceive(t){return Ce(this,void 0,void 0,function*(){return t.includes("[MD]")&&t.includes("[/MD]")?t:dt(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 "}}
|
|
2504
2735
|
/**
|
|
2505
2736
|
* @license
|
|
2506
2737
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2507
2738
|
* SPDX-License-Identifier: MIT
|
|
2508
|
-
*/var Te=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Ee extends ke{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 Te(this,void 0,void 0,function*(){try{const e=JSON.parse(t);if("flight"===e.type||this.isFlightData(e))return this.renderFlightCard(e)}catch(t){}const e=/\[FLIGHT\]([\s\S]*?)\[\/FLIGHT\]/g;let n,i=t;for(;null!==(n=e.exec(t));)try{const t=JSON.parse(n[1]),e=this.renderFlightCard(t);i=i.replace(n[0],e)}catch(t){console.warn("[FlightCardPlugin] Failed to parse flight data:",t)}return i})}renderHtmlBlock(t,e){if("flight"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderFlightCard(t)}catch(t){return console.warn("[FlightCardPlugin] renderHtmlBlock parse error:",t),""}}isFlightData(t){return t&&"object"==typeof t&&t.origin&&t.destination&&t.departureTime}renderFlightCard(t){const{origin:e,destination:n,departureTime:i,arrivalTime:o,departureDate:s,arrivalDate:r,terminal:a,gate:l,arrivalTerminal:d,arrivalGate:c,duration:h,flightNumber:u,airline:p,status:f,updated:g,source:m}=t;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-flight-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__route">\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(e)}</span>\n <div class="${this.cssPrefix}__flight-line">\n <svg class="${this.cssPrefix}__plane-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" fill="currentColor"/>\n </svg>\n ${h?`<span class="${this.cssPrefix}__duration">${this.escapeHtml(h)}</span>`:""}\n </div>\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(n)}</span>\n </div>\n ${u||p?`\n <div class="${this.cssPrefix}__flight-info">\n ${p?`<span class="${this.cssPrefix}__airline">${this.escapeHtml(p)}</span>`:""}\n ${u?`<span class="${this.cssPrefix}__flight-number">${this.escapeHtml(u)}</span>`:""}\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--departure">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(e)}</span>\n <span class="${this.cssPrefix}__date">${s?this.escapeHtml(s):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure de départ prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(i)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${a?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(a)}</span>\n </div>\n `:""}\n ${l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(l)}</span>\n </div>\n `:void 0===l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n\n <div class="${this.cssPrefix}__divider"></div>\n\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--arrival">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(n)}</span>\n <span class="${this.cssPrefix}__date">${r?this.escapeHtml(r):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure d'arrivée prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(o)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${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 ${g||m||f?`\n <div class="${this.cssPrefix}__footer">\n ${g?`<span class="${this.cssPrefix}__updated">${this.escapeHtml(g)}</span>`:""}\n ${m?`<span class="${this.cssPrefix}__source">Source : ${this.escapeHtml(m)}</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 `}}
|
|
2739
|
+
*/var Oe=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class Ie extends Ee{constructor(){super(...arguments),this.id="flight-card",this.name="Flight Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"flight",open:"[FLIGHT]",close:"[/FLIGHT]"}],this.cssPrefix="nr-flight-card"}renderHtmlBlockPlaceholder(t){if("flight"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`flight-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n style="min-width: 400px; max-width: 600px; margin: 16px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[FlightCardPlugin] Initialized")}afterReceive(t){return Oe(this,void 0,void 0,function*(){try{const e=JSON.parse(t);if("flight"===e.type||this.isFlightData(e))return this.renderFlightCard(e)}catch(t){}const e=/\[FLIGHT\]([\s\S]*?)\[\/FLIGHT\]/g;let n,i=t;for(;null!==(n=e.exec(t));)try{const t=JSON.parse(n[1]),e=this.renderFlightCard(t);i=i.replace(n[0],e)}catch(t){console.warn("[FlightCardPlugin] Failed to parse flight data:",t)}return i})}renderHtmlBlock(t,e){if("flight"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderFlightCard(t)}catch(t){return console.warn("[FlightCardPlugin] renderHtmlBlock parse error:",t),""}}isFlightData(t){return t&&"object"==typeof t&&t.origin&&t.destination&&t.departureTime}renderFlightCard(t){const{origin:e,destination:n,departureTime:i,arrivalTime:o,departureDate:s,arrivalDate:r,terminal:a,gate:l,arrivalTerminal:c,arrivalGate:d,duration:h,flightNumber:u,airline:p,status:f,updated:g,source:m}=t;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-flight-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__route">\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(e)}</span>\n <div class="${this.cssPrefix}__flight-line">\n <svg class="${this.cssPrefix}__plane-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" fill="currentColor"/>\n </svg>\n ${h?`<span class="${this.cssPrefix}__duration">${this.escapeHtml(h)}</span>`:""}\n </div>\n <span class="${this.cssPrefix}__airport-code">${this.escapeHtml(n)}</span>\n </div>\n ${u||p?`\n <div class="${this.cssPrefix}__flight-info">\n ${p?`<span class="${this.cssPrefix}__airline">${this.escapeHtml(p)}</span>`:""}\n ${u?`<span class="${this.cssPrefix}__flight-number">${this.escapeHtml(u)}</span>`:""}\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--departure">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(e)}</span>\n <span class="${this.cssPrefix}__date">${s?this.escapeHtml(s):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure de départ prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(i)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${a?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(a)}</span>\n </div>\n `:""}\n ${l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(l)}</span>\n </div>\n `:void 0===l?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n\n <div class="${this.cssPrefix}__divider"></div>\n\n <div class="${this.cssPrefix}__section ${this.cssPrefix}__section--arrival">\n <div class="${this.cssPrefix}__label">Infos sur l'aéroport</div>\n <div class="${this.cssPrefix}__location">\n <span class="${this.cssPrefix}__city">${this.getCityName(n)}</span>\n <span class="${this.cssPrefix}__date">${r?this.escapeHtml(r):""}</span>\n </div>\n <div class="${this.cssPrefix}__time-group">\n <div class="${this.cssPrefix}__time-label">Heure d'arrivée prévue</div>\n <div class="${this.cssPrefix}__time-value">${this.escapeHtml(o)}</div>\n </div>\n <div class="${this.cssPrefix}__terminal-gate">\n ${c?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Terminal</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(c)}</span>\n </div>\n `:""}\n ${d?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">${this.escapeHtml(d)}</span>\n </div>\n `:void 0===d?`\n <div class="${this.cssPrefix}__info-item">\n <span class="${this.cssPrefix}__info-label">Porte</span>\n <span class="${this.cssPrefix}__info-value">-</span>\n </div>\n `:""}\n </div>\n </div>\n </div>\n\n ${g||m||f?`\n <div class="${this.cssPrefix}__footer">\n ${g?`<span class="${this.cssPrefix}__updated">${this.escapeHtml(g)}</span>`:""}\n ${m?`<span class="${this.cssPrefix}__source">Source : ${this.escapeHtml(m)}</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 `}}
|
|
2509
2740
|
/**
|
|
2510
2741
|
* @license
|
|
2511
2742
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2512
2743
|
* SPDX-License-Identifier: MIT
|
|
2513
|
-
*/class Me extends ke{constructor(){super(...arguments),this.id="print-job-card",this.name="Print Job Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"printjob",open:"[PRINTJOB]",close:"[/PRINTJOB]"}],this.cssPrefix="nr-print-job-card"}renderHtmlBlockPlaceholder(t){if("printjob"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`printjob-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n avatar\n paragraph='{"rows":3}'\n style="min-width: 350px; max-width: 500px; margin: 8px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[PrintJobCardPlugin] Initialized")}renderHtmlBlock(t,e){if("printjob"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderPrintJobCard(t)}catch(t){return console.warn("[PrintJobCardPlugin] renderHtmlBlock parse error:",t),""}}renderPrintJobCard(t){const e=this.getStatusIcon(t.status),n=t.pagesPrinted&&t.totalPages?Math.round(t.pagesPrinted/t.totalPages*100):0;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-print-job-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__printer-icon">\n 🖨️\n </div>\n <div class="${this.cssPrefix}__header-content">\n <div class="${this.cssPrefix}__title">${this.escapeHtml(t.documentName)}</div>\n <div class="${this.cssPrefix}__subtitle">${this.escapeHtml(t.printerName)}</div>\n </div>\n <div class="${this.cssPrefix}__job-id">#${this.escapeHtml(t.jobId)}</div>\n </div>\n\n <div class="${this.cssPrefix}__status-row">\n <span class="${this.cssPrefix}__status-badge ${this.cssPrefix}__status-badge--${t.status}">\n ${e} ${this.formatStatus(t.status)}\n </span>\n ${t.priority&&"normal"!==t.priority?`\n <span class="${this.cssPrefix}__priority-badge ${this.cssPrefix}__priority-badge--${t.priority}">\n ${"high"===t.priority?"⚡":"🔽"} ${this.capitalize(t.priority)} Priority\n </span>\n `:""}\n </div>\n\n ${"printing"===t.status&&t.pagesPrinted&&t.totalPages?`\n <div class="${this.cssPrefix}__progress">\n <div class="${this.cssPrefix}__progress-bar">\n <div class="${this.cssPrefix}__progress-fill" style="width: ${n}%"></div>\n </div>\n <div class="${this.cssPrefix}__progress-text">\n ${t.pagesPrinted} / ${t.totalPages} pages (${n}%)\n </div>\n </div>\n `:""}\n\n ${"error"===t.status&&t.errorMessage?`\n <div class="${this.cssPrefix}__error-message">\n ⚠️ ${this.escapeHtml(t.errorMessage)}\n </div>\n `:""}\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Pages:</span>\n <span class="${this.cssPrefix}__detail-value">${t.totalPages}</span>\n </div>\n ${t.copies&&t.copies>1?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Copies:</span>\n <span class="${this.cssPrefix}__detail-value">${t.copies}</span>\n </div>\n `:""}\n ${t.colorMode?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Color Mode:</span>\n <span class="${this.cssPrefix}__detail-value">${this.capitalize(t.colorMode)}</span>\n </div>\n `:""}\n ${t.paperSize?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Paper Size:</span>\n <span class="${this.cssPrefix}__detail-value">${t.paperSize}</span>\n </div>\n `:""}\n ${t.userName?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">User:</span>\n <span class="${this.cssPrefix}__detail-value">${this.escapeHtml(t.userName)}</span>\n </div>\n `:""}\n ${t.estimatedTime&&"printing"===t.status?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Est. Time:</span>\n <span class="${this.cssPrefix}__detail-value">${t.estimatedTime}</span>\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__footer">\n <span class="${this.cssPrefix}__timestamp">\n 📅 Submitted: ${this.formatTimestamp(t.submittedAt)}\n </span>\n ${t.completedAt?`\n <span class="${this.cssPrefix}__timestamp">\n ✅ Completed: ${this.formatTimestamp(t.completedAt)}\n </span>\n `:""}\n </div>\n </div>\n `}getStatusColor(t){return{queued:"#ffa726",printing:"#42a5f5",completed:"#66bb6a",paused:"#ffb74d",error:"#ef5350",cancelled:"#78909c"}[t]||"#999"}getStatusIcon(t){return{queued:"⏳",printing:"🔄",completed:"✅",paused:"⏸️",error:"❌",cancelled:"🚫"}[t]||"📄"}formatStatus(t){return t.charAt(0).toUpperCase()+t.slice(1)}capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}formatTimestamp(t){try{return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(e){return t}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 20px;\n margin: 12px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 500px;\n border-left: 4px solid #42a5f5;\n }\n\n .${this.cssPrefix}__header {\n display: flex;\n align-items: flex-start;\n gap: 12px;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__printer-icon {\n font-size: 32px;\n line-height: 1;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__header-content {\n flex: 1;\n min-width: 0;\n }\n\n .${this.cssPrefix}__title {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n margin-bottom: 4px;\n word-break: break-word;\n }\n\n .${this.cssPrefix}__subtitle {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__job-id {\n font-size: 12px;\n color: #999;\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 4px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__status-row {\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__status-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__status-badge--queued {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--printing {\n background: #e3f2fd;\n color: #0d47a1;\n }\n\n .${this.cssPrefix}__status-badge--completed {\n background: #e8f5e9;\n color: #1b5e20;\n }\n\n .${this.cssPrefix}__status-badge--paused {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--error {\n background: #ffebee;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__status-badge--cancelled {\n background: #f5f5f5;\n color: #616161;\n }\n\n .${this.cssPrefix}__priority-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__priority-badge--high {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__priority-badge--low {\n background: #f5f5f5;\n color: #666;\n }\n\n .${this.cssPrefix}__progress {\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__progress-bar {\n width: 100%;\n height: 8px;\n background: #e0e0e0;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #42a5f5 0%, #1976d2 100%);\n transition: width 0.3s ease;\n border-radius: 4px;\n }\n\n .${this.cssPrefix}__progress-text {\n font-size: 13px;\n color: #666;\n text-align: center;\n }\n\n .${this.cssPrefix}__error-message {\n background: #ffebee;\n border-left: 3px solid #ef5350;\n padding: 12px;\n margin-bottom: 16px;\n border-radius: 4px;\n font-size: 13px;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 16px;\n padding: 16px;\n background: #f9f9f9;\n border-radius: 8px;\n }\n\n .${this.cssPrefix}__detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n }\n\n .${this.cssPrefix}__detail-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__detail-value {\n font-size: 13px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-top: 12px;\n border-top: 1px solid #e0e0e0;\n }\n\n .${this.cssPrefix}__timestamp {\n font-size: 11px;\n color: #999;\n }\n\n /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .${this.cssPrefix} {\n background: #2a2a2a;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n border-left-color: #42a5f5;\n }\n\n .${this.cssPrefix}__title,\n .${this.cssPrefix}__detail-value {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__subtitle,\n .${this.cssPrefix}__detail-label {\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__job-id {\n background: #3a3a3a;\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__details {\n background: #333;\n }\n\n .${this.cssPrefix}__progress-bar {\n background: #444;\n }\n\n .${this.cssPrefix}__footer {\n border-top-color: #444;\n }\n }\n\n /* Responsive design */\n @media (max-width: 480px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n }\n\n .${this.cssPrefix}__header {\n flex-wrap: wrap;\n }\n\n .${this.cssPrefix}__job-id {\n order: -1;\n width: 100%;\n }\n }\n `}}
|
|
2744
|
+
*/class Re extends Ee{constructor(){super(...arguments),this.id="print-job-card",this.name="Print Job Card Plugin",this.version="1.0.0",this.htmlTags=[{name:"printjob",open:"[PRINTJOB]",close:"[/PRINTJOB]"}],this.cssPrefix="nr-print-job-card"}renderHtmlBlockPlaceholder(t){if("printjob"!==t.toLowerCase())return"";return`<div data-placeholder-id="${`printjob-skeleton-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}"><nr-skeleton \n active \n avatar\n paragraph='{"rows":3}'\n style="min-width: 350px; max-width: 500px; margin: 8px 0;"\n ></nr-skeleton></div>`}onInit(){console.log("[PrintJobCardPlugin] Initialized")}renderHtmlBlock(t,e){if("printjob"!==t.toLowerCase())return"";try{const t=JSON.parse(e);return this.renderPrintJobCard(t)}catch(t){return console.warn("[PrintJobCardPlugin] renderHtmlBlock parse error:",t),""}}renderPrintJobCard(t){const e=this.getStatusIcon(t.status),n=t.pagesPrinted&&t.totalPages?Math.round(t.pagesPrinted/t.totalPages*100):0;return`\n ${this.getOncePerConversationStyleTag(this.getStyles())}\n <div class="${this.cssPrefix}" data-nr-print-job-card="true">\n <div class="${this.cssPrefix}__header">\n <div class="${this.cssPrefix}__printer-icon">\n 🖨️\n </div>\n <div class="${this.cssPrefix}__header-content">\n <div class="${this.cssPrefix}__title">${this.escapeHtml(t.documentName)}</div>\n <div class="${this.cssPrefix}__subtitle">${this.escapeHtml(t.printerName)}</div>\n </div>\n <div class="${this.cssPrefix}__job-id">#${this.escapeHtml(t.jobId)}</div>\n </div>\n\n <div class="${this.cssPrefix}__status-row">\n <span class="${this.cssPrefix}__status-badge ${this.cssPrefix}__status-badge--${t.status}">\n ${e} ${this.formatStatus(t.status)}\n </span>\n ${t.priority&&"normal"!==t.priority?`\n <span class="${this.cssPrefix}__priority-badge ${this.cssPrefix}__priority-badge--${t.priority}">\n ${"high"===t.priority?"⚡":"🔽"} ${this.capitalize(t.priority)} Priority\n </span>\n `:""}\n </div>\n\n ${"printing"===t.status&&t.pagesPrinted&&t.totalPages?`\n <div class="${this.cssPrefix}__progress">\n <div class="${this.cssPrefix}__progress-bar">\n <div class="${this.cssPrefix}__progress-fill" style="width: ${n}%"></div>\n </div>\n <div class="${this.cssPrefix}__progress-text">\n ${t.pagesPrinted} / ${t.totalPages} pages (${n}%)\n </div>\n </div>\n `:""}\n\n ${"error"===t.status&&t.errorMessage?`\n <div class="${this.cssPrefix}__error-message">\n ⚠️ ${this.escapeHtml(t.errorMessage)}\n </div>\n `:""}\n\n <div class="${this.cssPrefix}__details">\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Pages:</span>\n <span class="${this.cssPrefix}__detail-value">${t.totalPages}</span>\n </div>\n ${t.copies&&t.copies>1?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Copies:</span>\n <span class="${this.cssPrefix}__detail-value">${t.copies}</span>\n </div>\n `:""}\n ${t.colorMode?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Color Mode:</span>\n <span class="${this.cssPrefix}__detail-value">${this.capitalize(t.colorMode)}</span>\n </div>\n `:""}\n ${t.paperSize?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Paper Size:</span>\n <span class="${this.cssPrefix}__detail-value">${t.paperSize}</span>\n </div>\n `:""}\n ${t.userName?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">User:</span>\n <span class="${this.cssPrefix}__detail-value">${this.escapeHtml(t.userName)}</span>\n </div>\n `:""}\n ${t.estimatedTime&&"printing"===t.status?`\n <div class="${this.cssPrefix}__detail-row">\n <span class="${this.cssPrefix}__detail-label">Est. Time:</span>\n <span class="${this.cssPrefix}__detail-value">${t.estimatedTime}</span>\n </div>\n `:""}\n </div>\n\n <div class="${this.cssPrefix}__footer">\n <span class="${this.cssPrefix}__timestamp">\n 📅 Submitted: ${this.formatTimestamp(t.submittedAt)}\n </span>\n ${t.completedAt?`\n <span class="${this.cssPrefix}__timestamp">\n ✅ Completed: ${this.formatTimestamp(t.completedAt)}\n </span>\n `:""}\n </div>\n </div>\n `}getStatusColor(t){return{queued:"#ffa726",printing:"#42a5f5",completed:"#66bb6a",paused:"#ffb74d",error:"#ef5350",cancelled:"#78909c"}[t]||"#999"}getStatusIcon(t){return{queued:"⏳",printing:"🔄",completed:"✅",paused:"⏸️",error:"❌",cancelled:"🚫"}[t]||"📄"}formatStatus(t){return t.charAt(0).toUpperCase()+t.slice(1)}capitalize(t){return t.charAt(0).toUpperCase()+t.slice(1)}formatTimestamp(t){try{return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch(e){return t}}escapeHtml(t){const e=document.createElement("div");return e.textContent=t,e.innerHTML}getStyles(){return`\n .${this.cssPrefix} {\n background: #ffffff;\n border-radius: 12px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n padding: 20px;\n margin: 12px 0;\n font-family: system-ui, -apple-system, sans-serif;\n max-width: 500px;\n border-left: 4px solid #42a5f5;\n }\n\n .${this.cssPrefix}__header {\n display: flex;\n align-items: flex-start;\n gap: 12px;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__printer-icon {\n font-size: 32px;\n line-height: 1;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__header-content {\n flex: 1;\n min-width: 0;\n }\n\n .${this.cssPrefix}__title {\n font-size: 16px;\n font-weight: 600;\n color: #1a1a1a;\n margin-bottom: 4px;\n word-break: break-word;\n }\n\n .${this.cssPrefix}__subtitle {\n font-size: 13px;\n color: #666;\n }\n\n .${this.cssPrefix}__job-id {\n font-size: 12px;\n color: #999;\n font-family: 'Monaco', 'Courier New', monospace;\n background: #f5f5f5;\n padding: 4px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .${this.cssPrefix}__status-row {\n display: flex;\n gap: 8px;\n flex-wrap: wrap;\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__status-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 13px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__status-badge--queued {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--printing {\n background: #e3f2fd;\n color: #0d47a1;\n }\n\n .${this.cssPrefix}__status-badge--completed {\n background: #e8f5e9;\n color: #1b5e20;\n }\n\n .${this.cssPrefix}__status-badge--paused {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__status-badge--error {\n background: #ffebee;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__status-badge--cancelled {\n background: #f5f5f5;\n color: #616161;\n }\n\n .${this.cssPrefix}__priority-badge {\n display: inline-flex;\n align-items: center;\n gap: 4px;\n padding: 6px 12px;\n border-radius: 6px;\n font-size: 12px;\n font-weight: 500;\n }\n\n .${this.cssPrefix}__priority-badge--high {\n background: #fff3e0;\n color: #e65100;\n }\n\n .${this.cssPrefix}__priority-badge--low {\n background: #f5f5f5;\n color: #666;\n }\n\n .${this.cssPrefix}__progress {\n margin-bottom: 16px;\n }\n\n .${this.cssPrefix}__progress-bar {\n width: 100%;\n height: 8px;\n background: #e0e0e0;\n border-radius: 4px;\n overflow: hidden;\n margin-bottom: 8px;\n }\n\n .${this.cssPrefix}__progress-fill {\n height: 100%;\n background: linear-gradient(90deg, #42a5f5 0%, #1976d2 100%);\n transition: width 0.3s ease;\n border-radius: 4px;\n }\n\n .${this.cssPrefix}__progress-text {\n font-size: 13px;\n color: #666;\n text-align: center;\n }\n\n .${this.cssPrefix}__error-message {\n background: #ffebee;\n border-left: 3px solid #ef5350;\n padding: 12px;\n margin-bottom: 16px;\n border-radius: 4px;\n font-size: 13px;\n color: #b71c1c;\n }\n\n .${this.cssPrefix}__details {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 16px;\n padding: 16px;\n background: #f9f9f9;\n border-radius: 8px;\n }\n\n .${this.cssPrefix}__detail-row {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n }\n\n .${this.cssPrefix}__detail-label {\n font-size: 12px;\n color: #666;\n }\n\n .${this.cssPrefix}__detail-value {\n font-size: 13px;\n font-weight: 600;\n color: #1a1a1a;\n }\n\n .${this.cssPrefix}__footer {\n display: flex;\n flex-direction: column;\n gap: 4px;\n padding-top: 12px;\n border-top: 1px solid #e0e0e0;\n }\n\n .${this.cssPrefix}__timestamp {\n font-size: 11px;\n color: #999;\n }\n\n /* Dark mode support */\n @media (prefers-color-scheme: dark) {\n .${this.cssPrefix} {\n background: #2a2a2a;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);\n border-left-color: #42a5f5;\n }\n\n .${this.cssPrefix}__title,\n .${this.cssPrefix}__detail-value {\n color: #ffffff;\n }\n\n .${this.cssPrefix}__subtitle,\n .${this.cssPrefix}__detail-label {\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__job-id {\n background: #3a3a3a;\n color: #b0b0b0;\n }\n\n .${this.cssPrefix}__details {\n background: #333;\n }\n\n .${this.cssPrefix}__progress-bar {\n background: #444;\n }\n\n .${this.cssPrefix}__footer {\n border-top-color: #444;\n }\n }\n\n /* Responsive design */\n @media (max-width: 480px) {\n .${this.cssPrefix} {\n padding: 16px;\n }\n\n .${this.cssPrefix}__details {\n grid-template-columns: 1fr;\n }\n\n .${this.cssPrefix}__header {\n flex-wrap: wrap;\n }\n\n .${this.cssPrefix}__job-id {\n order: -1;\n width: 100%;\n }\n }\n `}}
|
|
2514
2745
|
/**
|
|
2515
2746
|
* @license
|
|
2516
2747
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2517
2748
|
* SPDX-License-Identifier: MIT
|
|
2518
|
-
*/var
|
|
2749
|
+
*/var Ae=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class je extends Ee{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,n;try{const i=[...(null===(e=t.getMessages)||void 0===e?void 0:e.call(t))||[]].reverse().find(t=>t.sender===q.Bot);i&&!(null===(n=i.metadata)||void 0===n?void 0:n.hasArtifacts)&&this.processMessage(i)}catch(t){}})}onMessageReceived(t){return Ae(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 n=t.text;if(!n)return;const i=/```(\w*)\n([\s\S]*?)```/g;let o;const s=[];let r=0;for(;null!==(o=i.exec(n));){const e=(o[1]||"text").toLowerCase(),n=o[2],i=`artifact-${t.id}-${r}`,a={id:i,language:e,content:n,title:this.extractTitle(n,e,r),messageId:t.id,index:r};s.push(a),this.artifacts.set(i,a),r++}if(0===s.length)return;let a=n,l=0;a=a.replaceAll(i,()=>`\0ARTIFACT_CARD_${s[l++].id}\0`),a=dt(a);for(const t of s)a=a.replace(`\0ARTIFACT_CARD_${t.id}\0`,this.renderPlaceholderCard(t));const c=this.getOncePerConversationStyleTag(this.getStyles());this.controller&&"function"==typeof this.controller.updateMessage&&this.controller.updateMessage(t.id,{text:c+a,metadata:Object.assign(Object.assign({},t.metadata),{renderAsHtml:!0,hasArtifacts:!0,artifactIds:s.map(t=>t.id),artifactOriginalText:n})})}rebuildArtifactsFromMetadata(t){var e,n;const i=null===(e=t.metadata)||void 0===e?void 0:e.artifactIds;if(!(null==i?void 0:i.length))return;if(i.every(t=>this.artifacts.has(t)))return;const o=null===(n=t.metadata)||void 0===n?void 0:n.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(),n=r[2],i=`artifact-${t.id}-${a}`,o=this.extractTitle(n,e,a);this.artifacts.set(i,{id:i,language:e,content:n,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,n){const i=t.trimStart().split("\n")[0]||"",o=[/^\/\/\s*(.+)/,/^#\s*(.+)/,/^--\s*(.+)/,/^\/\*\s*(.*?)\*\//,/^<!--\s*(.*?)-->/];for(const t of o){const e=t.exec(i);if(null==e?void 0:e[1]){const t=e[1].trim();if(t.length>0&&t.length<=60)return t}}return`${ct(e)} Snippet ${n+1}`}renderPlaceholderCard(t){const e=ct(t.language),n=at(t.title);return`<div class="nr-artifact-card" data-artifact-id="${t.id}" role="button" tabindex="0" aria-label="View ${n}">\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">${n}</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 "}}
|
|
2519
2750
|
/**
|
|
2520
2751
|
* @license
|
|
2521
2752
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2522
2753
|
* SPDX-License-Identifier: MIT
|
|
2523
|
-
*/class
|
|
2754
|
+
*/class De extends Ee{constructor(){super(...arguments),this.id="json-graph-renderer",this.name="JSON Graph Renderer",this.version="1.0.0"}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}if(null===e||"object"!=typeof e)return"";const n=Array.isArray(e)?e.map((t,e)=>this.renderNode(String(e),t)):Object.entries(e).map(([t,e])=>this.renderNode(t,e));return`\n <div style="padding:20px;font-family:system-ui,-apple-system,sans-serif;overflow:auto;">\n <div style="\n display:flex;align-items:center;gap:8px;\n margin-bottom:16px;padding-bottom:12px;\n border-bottom:1px solid #e2e8f0;\n ">\n <span style="\n display:inline-flex;align-items:center;justify-content:center;\n width:28px;height:28px;border-radius:6px;\n background:linear-gradient(135deg,#0ea5e9,#8b5cf6);\n color:#fff;font-size:14px;font-weight:700;\n ">{}</span>\n <span style="font-size:15px;font-weight:600;color:#1e293b;">\n JSON Graph View\n </span>\n <span style="\n margin-left:auto;font-size:12px;padding:2px 8px;border-radius:10px;\n background:#f1f5f9;color:#64748b;\n ">${Array.isArray(e)?e.length:Object.keys(e).length} root keys</span>\n </div>\n ${n.join("")}\n </div>\n `}renderNode(t,e,n=0){const i=null!==e&&"object"==typeof e&&!Array.isArray(e),o=Array.isArray(e),s=24*n;if(!i&&!o)return`\n <div style="display:flex;align-items:center;gap:8px;margin-left:${s}px;margin-bottom:6px;">\n <span style="\n display:inline-block;width:8px;height:8px;border-radius:50%;\n background:${this.typeColor(e)};flex-shrink:0;\n "></span>\n <span style="font-weight:600;font-size:13px;color:#334155;">\n ${at(t)}\n </span>\n <span style="\n font-size:13px;padding:2px 8px;border-radius:4px;\n background:${this.typeBg(e)};color:${this.typeColor(e)};\n border:1px solid ${this.typeColor(e)}20;\n ">${at(this.formatValue(e))}</span>\n </div>\n `;const r=o?e.map((t,e)=>[String(e),t]):Object.entries(e),a=o?`[ ${r.length} ]`:`{ ${r.length} }`,l=o?"#8b5cf6":"#0ea5e9";return`\n <div style="margin-left:${s}px;margin-bottom:4px;">\n <div style="display:flex;align-items:center;gap:8px;margin-bottom:4px;">\n <span style="\n display:inline-flex;align-items:center;justify-content:center;\n width:20px;height:20px;border-radius:4px;\n background:${l}15;color:${l};font-size:11px;font-weight:700;\n border:1px solid ${l}30;\n ">${o?"[]":"{}"}</span>\n <span style="font-weight:600;font-size:13px;color:#334155;">\n ${at(t)}\n </span>\n <span style="\n font-size:11px;padding:1px 6px;border-radius:10px;\n background:${l}10;color:${l};font-weight:500;\n ">${a}</span>\n </div>\n <div style="margin-left:9px;padding-left:16px;border-left:2px solid #e2e8f0;">\n ${r.map(([t,e])=>this.renderNode(t,e,0)).join("")}\n </div>\n </div>\n `}typeColor(t){if(null===t)return"#94a3b8";switch(typeof t){case"string":return"#22c55e";case"number":return"#3b82f6";case"boolean":return"#f59e0b";default:return"#94a3b8"}}typeBg(t){if(null===t)return"#f1f5f9";switch(typeof t){case"string":return"#f0fdf4";case"number":return"#eff6ff";case"boolean":return"#fffbeb";default:return"#f1f5f9"}}formatValue(t){return null==t?"null":"string"==typeof t?`"${t}"`:"number"==typeof t||"boolean"==typeof t?String(t):JSON.stringify(t)}}
|
|
2524
2755
|
/**
|
|
2525
2756
|
* @license
|
|
2526
2757
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2527
2758
|
* SPDX-License-Identifier: MIT
|
|
2528
|
-
*/const Oe="nuraly:flow-diagram:split-width",Re="nuraly:flow-diagram:panel-width",je="nr-flow-diagram-editor";class Ae extends HTMLElement{connectedCallback(){var t;const e=this.loadPanelWidth(),n=this.closestPanel();n&&(n.style.setProperty("width",`${e}px`),this._panelObserver=new ResizeObserver(()=>{const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Re,String(t))}),this._panelObserver.observe(n));const i=this.attachShadow({mode:"open"}),o=null!==(t=this.getAttribute("content"))&&void 0!==t?t:"",s=this.unescapeHtml(o),r=this.prettyPrint(s);let a=null;try{a=JSON.parse(s)}catch(t){}i.innerHTML=`\n <style>${Ae.styles()}</style>\n ${this.renderHeader(a)}\n <div class="split">\n <div class="editor-pane">\n <textarea class="editor-textarea" spellcheck="false"></textarea>\n </div>\n <div class="resize-handle"><div class="resize-handle-bar"></div></div>\n <div class="diagram-pane">\n ${a?this.renderDiagram(a):'<div class="empty">Invalid JSON</div>'}\n </div>\n </div>\n <div class="error-bar" style="display:none;"></div>\n `;const l=i.querySelector(".editor-textarea");l&&(l.value=r);const d=localStorage.getItem(Oe);d&&requestAnimationFrame(()=>{const t=i.querySelector(".editor-pane");t&&(t.style.flex="none",t.style.width=`${d}px`)});const c=i.querySelector(".diagram-pane"),h=i.querySelector(".error-bar");l&&c&&h&&(l.addEventListener("input",()=>{try{const t=JSON.parse(l.value);if(t.Steps&&t.Transitions){c.innerHTML=this.renderDiagram(t);const e=i.querySelector(".header");if(e){const n=document.createElement("template");n.innerHTML=this.renderHeader(t).trim();const i=n.content.firstElementChild;i&&e.replaceWith(i)}}h.style.display="none"}catch(t){h.textContent=`Parse error: ${t.message}`,h.style.display="flex"}}),this.initResize(i))}disconnectedCallback(){var t,e;null===(t=this._panelObserver)||void 0===t||t.disconnect(),null===(e=this.closestPanel())||void 0===e||e.style.removeProperty("width")}loadPanelWidth(){const t=localStorage.getItem(Re);return t?Math.max(300,Number.parseInt(t,10)):500}closestPanel(){var t,e,n,i;let o=null!==(e=null!==(t=this.parentElement)&&void 0!==t?t:this.getRootNode().host)&&void 0!==e?e:null;for(;o;){if(o instanceof HTMLElement&&o.classList.contains("artifact-panel"))return o;o=null!==(i=null!==(n=o.parentElement)&&void 0!==n?n:o.getRootNode().host)&&void 0!==i?i:null}return null}initResize(t){const e=t.querySelector(".split"),n=t.querySelector(".editor-pane"),i=t.querySelector(".resize-handle");if(!e||!n||!i)return;let o=!1,s=0,r=0;const a=t=>{if(!o)return;const i=t.clientX-s,a=e.getBoundingClientRect().width,l=Math.max(200,Math.min(r+i,a-200));n.style.flex="none",n.style.width=`${l}px`},l=()=>{if(!o)return;o=!1,i.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="";const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Oe,String(t)),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};i.addEventListener("mousedown",t=>{const e=t;e.preventDefault(),o=!0,s=e.clientX,r=n.getBoundingClientRect().width,i.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)})}prettyPrint(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch(e){return t}}unescapeHtml(t){const e=document.createElement("textarea");return e.innerHTML=t,e.value}renderHeader(t){var e,n;const i=null!==(e=null==t?void 0:t.Name)&&void 0!==e?e:"Workflow",o=(null!==(n=null==t?void 0:t.DocflowTags)&&void 0!==n?n:[]).map(t=>`<span class="tag">${rt(t)}</span>`).join("");return`\n <div class="header">\n <span class="header-icon">⬡</span>\n <span class="header-name">${rt(i)}</span>\n ${o}\n </div>\n `}renderDiagram(t){var e,n;const i=this.buildOrderedSteps(t),o=[];for(let t=0;t<i.length;t++){const s=i[t];o.push("event"===s.type?this.renderEventNode(s.name,null!==(e=s.eventType)&&void 0!==e?e:""):this.renderStepNode(s.name,null!==(n=s.step)&&void 0!==n?n:{})),t<i.length-1&&o.push(this.renderConnector())}return`<div class="diagram">${o.join("")}</div>`}buildOrderedSteps(t){var e,n,i,o;const s=[],r=null===(e=t.Events)||void 0===e?void 0:e.StartEvent,a=null===(n=t.Events)||void 0===n?void 0:n.EndEvent;r&&s.push({type:"event",name:r.Name||"Start",eventType:"start"});const l={};for(const e of Object.values(t.Transitions))l[e.Source]=e;let d=null!==(o=null===(i=l.StartEvent)||void 0===i?void 0:i.Target)&&void 0!==o?o:Object.keys(t.Steps)[0];const c=new Set;for(;d&&t.Steps[d]&&!c.has(d);){c.add(d),s.push({type:"step",name:d,step:t.Steps[d]});const e=l[d];if(!e||"EndEvent"===e.Target)break;d=e.Target}return a&&s.push({type:"event",name:a.Name||"End",eventType:"end"}),s}renderEventNode(t,e){const n="start"===e;return`\n <div class="node event-node ${n?"event-start":"event-end"}">\n <span class="event-icon">${n?"●":"■"}</span>\n <span class="event-label">${rt(t)}</span>\n </div>\n `}renderStepNode(t,e){var n,i,o;const s=null!==(n=e.StepType)&&void 0!==n?n:"",r=null!==(o=null===(i=e.Description)||void 0===i?void 0:i.trim())&&void 0!==o?o:"",a=s?`<span class="step-badge ${"Worker"===s?"badge-worker":"badge-system"}">${rt(s)}</span>`:"",l=r?`<div class="step-desc">${rt(r)}</div>`:"";return`\n <div class="node step-node">\n <div class="step-header">\n <span class="step-name">${rt(t)}</span>\n ${a}\n </div>\n ${l}\n </div>\n `}renderConnector(){return'\n <div class="connector">\n <div class="connector-line"></div>\n <div class="connector-arrow">▼</div>\n </div>\n '}static styles(){return"\n :host {\n display: flex;\n flex-direction: column;\n width: 100%;\n min-width: 480px;\n height: 100%;\n font-family: system-ui, -apple-system, sans-serif;\n color: #1e293b;\n overflow: hidden;\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 12px 16px;\n border-bottom: 1px solid #e2e8f0;\n background: #f8fafc;\n flex-shrink: 0;\n }\n .header-icon { font-size: 18px; color: #6366f1; }\n .header-name { font-weight: 600; font-size: 15px; }\n .tag {\n font-size: 11px;\n padding: 2px 8px;\n border-radius: 10px;\n background: #ede9fe;\n color: #6366f1;\n font-weight: 500;\n }\n\n .split {\n display: flex;\n flex: 1;\n min-height: 0;\n }\n\n .editor-pane {\n flex: 1;\n min-width: 200px;\n display: flex;\n overflow: hidden;\n }\n .editor-textarea {\n flex: 1;\n width: 100%;\n height: 100%;\n border: none;\n outline: none;\n resize: none;\n padding: 12px;\n font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;\n font-size: 12px;\n line-height: 1.6;\n color: #1e293b;\n background: #ffffff;\n box-sizing: border-box;\n tab-size: 2;\n }\n\n /* ── Resize handle ──────────────────────────────── */\n\n .resize-handle {\n flex-shrink: 0;\n width: 8px;\n cursor: col-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #f1f5f9;\n border-left: 1px solid #e2e8f0;\n border-right: 1px solid #e2e8f0;\n transition: background 0.15s;\n }\n .resize-handle:hover,\n .resize-handle.active { background: #e2e8f0; }\n .resize-handle-bar {\n width: 2px;\n height: 24px;\n border-radius: 1px;\n background: #cbd5e1;\n transition: background 0.15s;\n }\n .resize-handle:hover .resize-handle-bar,\n .resize-handle.active .resize-handle-bar { background: #94a3b8; }\n\n .diagram-pane {\n flex: 1;\n min-width: 200px;\n overflow-y: auto;\n padding: 24px;\n background: #f8fafc;\n }\n\n .diagram {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n color: #94a3b8;\n font-size: 14px;\n }\n\n /* ── Event nodes ──────────────────────────────────── */\n\n .event-node {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 20px;\n border-radius: 20px;\n font-size: 13px;\n font-weight: 600;\n }\n .event-start { background: #ecfdf5; border: 1.5px solid #86efac; color: #166534; }\n .event-start .event-icon { color: #22c55e; font-size: 10px; }\n .event-end { background: #fef2f2; border: 1.5px solid #fca5a5; color: #991b1b; }\n .event-end .event-icon { color: #ef4444; font-size: 10px; }\n\n /* ── Step nodes ───────────────────────────────────── */\n\n .step-node {\n width: 220px;\n padding: 12px 16px;\n border-radius: 8px;\n background: #ffffff;\n border: 1.5px solid #e2e8f0;\n box-shadow: 0 1px 3px rgba(0,0,0,0.06);\n }\n .step-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n }\n .step-name { font-weight: 600; font-size: 13px; color: #1e293b; }\n .step-badge {\n font-size: 10px;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.02em;\n flex-shrink: 0;\n }\n .badge-worker { background: #dbeafe; color: #1d4ed8; }\n .badge-system { background: #fef3c7; color: #92400e; }\n .step-desc { margin-top: 6px; font-size: 11px; color: #64748b; line-height: 1.4; }\n\n /* ── Connectors ───────────────────────────────────── */\n\n .connector {\n display: flex;\n flex-direction: column;\n align-items: center;\n height: 32px;\n }\n .connector-line { width: 2px; flex: 1; background: #cbd5e1; }\n .connector-arrow { font-size: 8px; color: #cbd5e1; line-height: 1; margin-top: -2px; }\n\n /* ── Error bar ────────────────────────────────────── */\n\n .error-bar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 8px 16px;\n background: #fef2f2;\n border-top: 1px solid #fecaca;\n color: #dc2626;\n font-size: 12px;\n flex-shrink: 0;\n }\n .error-bar::before { content: '⚠'; }\n "}}class De extends ke{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(je)||customElements.define(je,Ae)}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}return null!==e&&"object"==typeof e&&e.Steps&&"object"==typeof e.Steps&&e.Transitions&&"object"==typeof e.Transitions?`<nr-flow-diagram-editor content="${rt(t.content)}"></nr-flow-diagram-editor>`:""}}
|
|
2759
|
+
*/const Fe="nuraly:flow-diagram:split-width",Ne="nuraly:flow-diagram:panel-width",Be="nr-flow-diagram-editor";class Le extends HTMLElement{connectedCallback(){var t;const e=this.loadPanelWidth(),n=this.closestPanel();n&&(n.style.setProperty("width",`${e}px`),this._panelObserver=new ResizeObserver(()=>{const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Ne,String(t))}),this._panelObserver.observe(n));const i=this.attachShadow({mode:"open"}),o=null!==(t=this.getAttribute("content"))&&void 0!==t?t:"",s=this.unescapeHtml(o),r=this.prettyPrint(s);let a=null;try{a=JSON.parse(s)}catch(t){}i.innerHTML=`\n <style>${Le.styles()}</style>\n ${this.renderHeader(a)}\n <div class="split">\n <div class="editor-pane">\n <textarea class="editor-textarea" spellcheck="false"></textarea>\n </div>\n <div class="resize-handle"><div class="resize-handle-bar"></div></div>\n <div class="diagram-pane">\n ${a?this.renderDiagram(a):'<div class="empty">Invalid JSON</div>'}\n </div>\n </div>\n <div class="error-bar" style="display:none;"></div>\n `;const l=i.querySelector(".editor-textarea");l&&(l.value=r);const c=localStorage.getItem(Fe);c&&requestAnimationFrame(()=>{const t=i.querySelector(".editor-pane");t&&(t.style.flex="none",t.style.width=`${c}px`)});const d=i.querySelector(".diagram-pane"),h=i.querySelector(".error-bar");l&&d&&h&&(l.addEventListener("input",()=>{try{const t=JSON.parse(l.value);if(t.Steps&&t.Transitions){d.innerHTML=this.renderDiagram(t);const e=i.querySelector(".header");if(e){const n=document.createElement("template");n.innerHTML=this.renderHeader(t).trim();const i=n.content.firstElementChild;i&&e.replaceWith(i)}}h.style.display="none"}catch(t){h.textContent=`Parse error: ${t.message}`,h.style.display="flex"}}),this.initResize(i))}disconnectedCallback(){var t,e;null===(t=this._panelObserver)||void 0===t||t.disconnect(),null===(e=this.closestPanel())||void 0===e||e.style.removeProperty("width")}loadPanelWidth(){const t=localStorage.getItem(Ne);return t?Math.max(300,Number.parseInt(t,10)):500}closestPanel(){var t,e,n,i;let o=null!==(e=null!==(t=this.parentElement)&&void 0!==t?t:this.getRootNode().host)&&void 0!==e?e:null;for(;o;){if(o instanceof HTMLElement&&o.classList.contains("artifact-panel"))return o;o=null!==(i=null!==(n=o.parentElement)&&void 0!==n?n:o.getRootNode().host)&&void 0!==i?i:null}return null}initResize(t){const e=t.querySelector(".split"),n=t.querySelector(".editor-pane"),i=t.querySelector(".resize-handle");if(!e||!n||!i)return;let o=!1,s=0,r=0;const a=t=>{if(!o)return;const i=t.clientX-s,a=e.getBoundingClientRect().width,l=Math.max(200,Math.min(r+i,a-200));n.style.flex="none",n.style.width=`${l}px`},l=()=>{if(!o)return;o=!1,i.classList.remove("active"),document.body.style.cursor="",document.body.style.userSelect="";const t=Math.round(n.getBoundingClientRect().width);t>=200&&localStorage.setItem(Fe,String(t)),document.removeEventListener("mousemove",a),document.removeEventListener("mouseup",l)};i.addEventListener("mousedown",t=>{const e=t;e.preventDefault(),o=!0,s=e.clientX,r=n.getBoundingClientRect().width,i.classList.add("active"),document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",a),document.addEventListener("mouseup",l)})}prettyPrint(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch(e){return t}}unescapeHtml(t){const e=document.createElement("textarea");return e.innerHTML=t,e.value}renderHeader(t){var e,n;const i=null!==(e=null==t?void 0:t.Name)&&void 0!==e?e:"Workflow",o=(null!==(n=null==t?void 0:t.DocflowTags)&&void 0!==n?n:[]).map(t=>`<span class="tag">${at(t)}</span>`).join("");return`\n <div class="header">\n <span class="header-icon">⬡</span>\n <span class="header-name">${at(i)}</span>\n ${o}\n </div>\n `}renderDiagram(t){var e,n;const i=this.buildOrderedSteps(t),o=[];for(let t=0;t<i.length;t++){const s=i[t];o.push("event"===s.type?this.renderEventNode(s.name,null!==(e=s.eventType)&&void 0!==e?e:""):this.renderStepNode(s.name,null!==(n=s.step)&&void 0!==n?n:{})),t<i.length-1&&o.push(this.renderConnector())}return`<div class="diagram">${o.join("")}</div>`}buildOrderedSteps(t){var e,n,i,o;const s=[],r=null===(e=t.Events)||void 0===e?void 0:e.StartEvent,a=null===(n=t.Events)||void 0===n?void 0:n.EndEvent;r&&s.push({type:"event",name:r.Name||"Start",eventType:"start"});const l={};for(const e of Object.values(t.Transitions))l[e.Source]=e;let c=null!==(o=null===(i=l.StartEvent)||void 0===i?void 0:i.Target)&&void 0!==o?o:Object.keys(t.Steps)[0];const d=new Set;for(;c&&t.Steps[c]&&!d.has(c);){d.add(c),s.push({type:"step",name:c,step:t.Steps[c]});const e=l[c];if(!e||"EndEvent"===e.Target)break;c=e.Target}return a&&s.push({type:"event",name:a.Name||"End",eventType:"end"}),s}renderEventNode(t,e){const n="start"===e;return`\n <div class="node event-node ${n?"event-start":"event-end"}">\n <span class="event-icon">${n?"●":"■"}</span>\n <span class="event-label">${at(t)}</span>\n </div>\n `}renderStepNode(t,e){var n,i,o;const s=null!==(n=e.StepType)&&void 0!==n?n:"",r=null!==(o=null===(i=e.Description)||void 0===i?void 0:i.trim())&&void 0!==o?o:"",a=s?`<span class="step-badge ${"Worker"===s?"badge-worker":"badge-system"}">${at(s)}</span>`:"",l=r?`<div class="step-desc">${at(r)}</div>`:"";return`\n <div class="node step-node">\n <div class="step-header">\n <span class="step-name">${at(t)}</span>\n ${a}\n </div>\n ${l}\n </div>\n `}renderConnector(){return'\n <div class="connector">\n <div class="connector-line"></div>\n <div class="connector-arrow">▼</div>\n </div>\n '}static styles(){return"\n :host {\n display: flex;\n flex-direction: column;\n width: 100%;\n min-width: 480px;\n height: 100%;\n font-family: system-ui, -apple-system, sans-serif;\n color: #1e293b;\n overflow: hidden;\n }\n\n .header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 12px 16px;\n border-bottom: 1px solid #e2e8f0;\n background: #f8fafc;\n flex-shrink: 0;\n }\n .header-icon { font-size: 18px; color: #6366f1; }\n .header-name { font-weight: 600; font-size: 15px; }\n .tag {\n font-size: 11px;\n padding: 2px 8px;\n border-radius: 10px;\n background: #ede9fe;\n color: #6366f1;\n font-weight: 500;\n }\n\n .split {\n display: flex;\n flex: 1;\n min-height: 0;\n }\n\n .editor-pane {\n flex: 1;\n min-width: 200px;\n display: flex;\n overflow: hidden;\n }\n .editor-textarea {\n flex: 1;\n width: 100%;\n height: 100%;\n border: none;\n outline: none;\n resize: none;\n padding: 12px;\n font-family: 'Fira Code', 'Cascadia Code', Consolas, monospace;\n font-size: 12px;\n line-height: 1.6;\n color: #1e293b;\n background: #ffffff;\n box-sizing: border-box;\n tab-size: 2;\n }\n\n /* ── Resize handle ──────────────────────────────── */\n\n .resize-handle {\n flex-shrink: 0;\n width: 8px;\n cursor: col-resize;\n display: flex;\n align-items: center;\n justify-content: center;\n background: #f1f5f9;\n border-left: 1px solid #e2e8f0;\n border-right: 1px solid #e2e8f0;\n transition: background 0.15s;\n }\n .resize-handle:hover,\n .resize-handle.active { background: #e2e8f0; }\n .resize-handle-bar {\n width: 2px;\n height: 24px;\n border-radius: 1px;\n background: #cbd5e1;\n transition: background 0.15s;\n }\n .resize-handle:hover .resize-handle-bar,\n .resize-handle.active .resize-handle-bar { background: #94a3b8; }\n\n .diagram-pane {\n flex: 1;\n min-width: 200px;\n overflow-y: auto;\n padding: 24px;\n background: #f8fafc;\n }\n\n .diagram {\n display: flex;\n flex-direction: column;\n align-items: center;\n }\n\n .empty {\n display: flex;\n align-items: center;\n justify-content: center;\n height: 100%;\n color: #94a3b8;\n font-size: 14px;\n }\n\n /* ── Event nodes ──────────────────────────────────── */\n\n .event-node {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 20px;\n border-radius: 20px;\n font-size: 13px;\n font-weight: 600;\n }\n .event-start { background: #ecfdf5; border: 1.5px solid #86efac; color: #166534; }\n .event-start .event-icon { color: #22c55e; font-size: 10px; }\n .event-end { background: #fef2f2; border: 1.5px solid #fca5a5; color: #991b1b; }\n .event-end .event-icon { color: #ef4444; font-size: 10px; }\n\n /* ── Step nodes ───────────────────────────────────── */\n\n .step-node {\n width: 220px;\n padding: 12px 16px;\n border-radius: 8px;\n background: #ffffff;\n border: 1.5px solid #e2e8f0;\n box-shadow: 0 1px 3px rgba(0,0,0,0.06);\n }\n .step-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 8px;\n }\n .step-name { font-weight: 600; font-size: 13px; color: #1e293b; }\n .step-badge {\n font-size: 10px;\n padding: 2px 6px;\n border-radius: 4px;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.02em;\n flex-shrink: 0;\n }\n .badge-worker { background: #dbeafe; color: #1d4ed8; }\n .badge-system { background: #fef3c7; color: #92400e; }\n .step-desc { margin-top: 6px; font-size: 11px; color: #64748b; line-height: 1.4; }\n\n /* ── Connectors ───────────────────────────────────── */\n\n .connector {\n display: flex;\n flex-direction: column;\n align-items: center;\n height: 32px;\n }\n .connector-line { width: 2px; flex: 1; background: #cbd5e1; }\n .connector-arrow { font-size: 8px; color: #cbd5e1; line-height: 1; margin-top: -2px; }\n\n /* ── Error bar ────────────────────────────────────── */\n\n .error-bar {\n display: flex;\n align-items: center;\n gap: 6px;\n padding: 8px 16px;\n background: #fef2f2;\n border-top: 1px solid #fecaca;\n color: #dc2626;\n font-size: 12px;\n flex-shrink: 0;\n }\n .error-bar::before { content: '⚠'; }\n "}}class Ue extends Ee{constructor(){super(...arguments),this.id="flow-diagram",this.name="Flow Diagram",this.version="1.0.0"}onInit(){customElements.get(Be)||customElements.define(Be,Le)}renderArtifactContent(t){if("json"!==t.language)return"";let e;try{e=JSON.parse(t.content)}catch(t){return""}return null!==e&&"object"==typeof e&&e.Steps&&"object"==typeof e.Steps&&e.Transitions&&"object"==typeof e.Transitions?`<nr-flow-diagram-editor content="${at(t.content)}"></nr-flow-diagram-editor>`:""}}
|
|
2529
2760
|
/**
|
|
2530
2761
|
* @license
|
|
2531
2762
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2532
2763
|
* SPDX-License-Identifier: MIT
|
|
2533
|
-
*/var
|
|
2764
|
+
*/var We=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class He extends Ee{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 We(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 n,i=t;for(;null!==(n=e.exec(t));)try{const t=JSON.parse(n[1]),e=this.renderSelectionCard(t);i=i.replace(n[0],e)}catch(t){console.warn("[SelectionCardPlugin] Failed to parse selection data:",t)}return i})}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:n,columns:i=1}=t,o=this.getOncePerConversationStyleTag(this.getStyles()),s=n.map(t=>{const e=t.disabled?'aria-disabled="true"':"",n=t.disabled?`${this.cssPrefix}__option--disabled`:"",i=t.disabled?"-1":"0",o=t.disabled?"":`data-selection-value="${this.escapeHtml(t.value)}"`;return`\n <div class="${this.cssPrefix}__option ${n}"\n ${o}\n role="button"\n tabindex="${i}"\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-${i}">\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 `}}
|
|
2534
2765
|
/**
|
|
2535
2766
|
* @license
|
|
2536
2767
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2537
2768
|
* SPDX-License-Identifier: MIT
|
|
2538
|
-
*/var
|
|
2769
|
+
*/var Je=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};class qe{constructor(){this.store=new Map}save(t,e){return Je(this,void 0,void 0,function*(){this.store.set(t,JSON.parse(JSON.stringify(e)))})}load(t){return Je(this,void 0,void 0,function*(){const e=this.store.get(t);return e?JSON.parse(JSON.stringify(e)):null})}remove(t){return Je(this,void 0,void 0,function*(){this.store.delete(t)})}clear(){return Je(this,void 0,void 0,function*(){this.store.clear()})}has(t){return Je(this,void 0,void 0,function*(){return this.store.has(t)})}}class Ve{save(t,e){return Je(this,void 0,void 0,function*(){try{localStorage.setItem(t,JSON.stringify(e))}catch(t){throw console.error("[LocalStorage] Save error:",t),new Error(`Failed to save to localStorage: ${t}`)}})}load(t){return Je(this,void 0,void 0,function*(){try{const e=localStorage.getItem(t);return e?JSON.parse(e):null}catch(t){return console.error("[LocalStorage] Load error:",t),null}})}remove(t){return Je(this,void 0,void 0,function*(){localStorage.removeItem(t)})}clear(){return Je(this,void 0,void 0,function*(){Object.keys(localStorage).filter(t=>t.startsWith("chatbot-")).forEach(t=>{localStorage.removeItem(t)})})}has(t){return Je(this,void 0,void 0,function*(){return null!==localStorage.getItem(t)})}}class Ge{constructor(t="chatbot-db",e="chatbot-store"){this.dbName=t,this.storeName=e}getDB(){return Je(this,void 0,void 0,function*(){return this.db?this.db:new Promise((t,e)=>{const n=indexedDB.open(this.dbName,1);n.onerror=()=>e(n.error),n.onsuccess=()=>{this.db=n.result,t(this.db)},n.onupgradeneeded=t=>{const e=t.target.result;e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName)}})})}save(t,e){return Je(this,void 0,void 0,function*(){const n=yield this.getDB();return new Promise((i,o)=>{const s=n.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(e,t);s.onerror=()=>o(s.error),s.onsuccess=()=>i()})})}load(t){return Je(this,void 0,void 0,function*(){const e=yield this.getDB();return new Promise((n,i)=>{const o=e.transaction([this.storeName],"readonly").objectStore(this.storeName).get(t);o.onerror=()=>i(o.error),o.onsuccess=()=>n(o.result||null)})})}remove(t){return Je(this,void 0,void 0,function*(){const e=yield this.getDB();return new Promise((n,i)=>{const o=e.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(t);o.onerror=()=>i(o.error),o.onsuccess=()=>n()})})}clear(){return Je(this,void 0,void 0,function*(){const t=yield this.getDB();return new Promise((e,n)=>{const i=t.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();i.onerror=()=>n(i.error),i.onsuccess=()=>e()})})}has(t){return Je(this,void 0,void 0,function*(){return null!==(yield this.load(t))})}}
|
|
2539
2770
|
/**
|
|
2540
2771
|
* @license
|
|
2541
2772
|
* Copyright 2023 Nuraly, Laabidi Aymen
|
|
2542
2773
|
* SPDX-License-Identifier: MIT
|
|
2543
|
-
*/class
|
|
2774
|
+
*/class Ke{constructor(t){this.host=t,t.addController(this)}hostConnected(){}hostDisconnected(){}handleMessagesUpdate(){var t;if(!this.host.autoScroll)return;(null===(t=this.host.shadowRoot)||void 0===t?void 0:t.querySelector(".messages"))&&this.scrollToBottom()}scrollToBottom(){var t;const e=null===(t=this.host.shadowRoot)||void 0===t?void 0:t.querySelector(".messages");e&&requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight})}}
|
|
2775
|
+
/**
|
|
2776
|
+
* @license
|
|
2777
|
+
* Copyright 2024 Nuraly, Laabidi Aymen
|
|
2778
|
+
* SPDX-License-Identifier: MIT
|
|
2779
|
+
*
|
|
2780
|
+
* Re-encodes any browser-recorded audio blob to OGG Opus at 32 kbps.
|
|
2781
|
+
* Falls back to the original blob unchanged on browsers that do not support
|
|
2782
|
+
* OGG Opus MediaRecorder recording (e.g. Safari).
|
|
2783
|
+
*
|
|
2784
|
+
* Pipeline:
|
|
2785
|
+
* input blob → AudioContext.decodeAudioData → BufferSource → MediaStreamDestination
|
|
2786
|
+
* → MediaRecorder(ogg/opus, 32 kbps) → output blob
|
|
2787
|
+
*/var Ye=function(t,e,n,i){return new(n||(n=Promise))(function(o,s){function r(t){try{l(i.next(t))}catch(t){s(t)}}function a(t){try{l(i.throw(t))}catch(t){s(t)}}function l(t){var e;t.done?o(t.value):(e=t.value,e instanceof n?e:new n(function(t){t(e)})).then(r,a)}l((i=i.apply(t,e||[])).next())})};const Xe="audio/ogg;codecs=opus";function Qe(){try{return"undefined"!=typeof MediaRecorder&&MediaRecorder.isTypeSupported(Xe)}catch(t){return!1}}var Ze=Object.freeze({__proto__:null,canEncodeOgg:Qe,compressToOpus:function(t,e){return Ye(this,void 0,void 0,function*(){if(!Qe()){const n=e.includes("mp4")?"mp4":e.includes("aac")?"aac":"webm";return{blob:t,mimeType:e,ext:n}}const n=yield t.arrayBuffer(),i=new AudioContext;let o;try{o=yield i.decodeAudioData(n)}finally{i.close().catch(()=>{})}const s=new AudioContext({sampleRate:o.sampleRate}),r=s.createMediaStreamDestination(),a=new MediaRecorder(r.stream,{mimeType:Xe,audioBitsPerSecond:32e3}),l=[];a.ondataavailable=t=>{t.data.size>0&&l.push(t.data)};const c=new Promise((t,e)=>{a.onstop=()=>t(),a.onerror=t=>{var n;return e(null!==(n=t.error)&&void 0!==n?n:new Error("MediaRecorder error"))}});a.start(100);const d=s.createBufferSource();return d.buffer=o,d.connect(r),d.onended=()=>{setTimeout(()=>{"recording"===a.state&&a.stop()},120)},d.start(0),yield c,s.close().catch(()=>{}),{blob:new Blob(l,{type:Xe}),mimeType:Xe,ext:"ogg"}})}});export{Te as AnalyticsPlugin,je as ArtifactPlugin,Ee as ChatPluginBase,Q as ChatbotActionType,Kt as ChatbotCoreController,X as ChatbotFileType,V as ChatbotLoadingType,Y as ChatbotMessageState,Ke as ChatbotScrollController,q as ChatbotSender,G as ChatbotSize,K as ChatbotVariant,ie as CustomAPIProvider,ot as DEFAULT_ALLOWED_FILE_TYPES,it as DEFAULT_MAX_FILES,nt as DEFAULT_MAX_FILE_SIZE,et as DEFAULT_MAX_MESSAGES,tt as DEFAULT_TYPING_DELAY,Z as EMPTY_STRING,Tt as EventBus,st as FILE_TYPE_MAPPINGS,At as FileHandler,Ie as FlightCardPlugin,Ue as FlowDiagramPlugin,Ge as IndexedDBStorage,De as JsonGraphRendererPlugin,Ve as LocalStorageAdapter,ze as MarkdownPlugin,qe as MemoryStorage,zt as MessageHandler,de as MockProvider,he as MockProviders,jt as ModuleHandler,Se as NativeWebSocketProvider,Mt as NrChatbotElement,Zt as OpenAIProvider,Me as PersistencePlugin,Jt as PluginService,Re as PrintJobCardPlugin,Nt as ProviderService,He as SelectionCardPlugin,me as SocketProvider,Ct as StateHandler,Wt as StorageService,Dt as SuggestionHandler,It as ThreadHandler,Et as ValidationError,Lt as ValidationService,xe as WorkflowSocketProvider};
|