all files / spreadsheet/integrations/ ai-assist.js

95.11% Statements 875/920
87.24% Branches 554/635
99.16% Functions 118/119
94.79% Lines 819/864
63 statements, 12 functions, 62 branches Ignored     
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464                                                                                                                                                                                                                                                                                                                                                                                                                                                          29× 29× 29× 174×   29× 29× 29× 29×   59× 30× 30× 30×         27× 27×                                                 27× 27×   30× 30×   30×   29× 29× 29×   29×         15×       12× 12×   12× 12×                           12× 12× 12× 12× 12×                                                                                                                               15×   13× 13× 13× 13× 13×   13×   13× 13× 13×   13×           13×   13×   13×   13× 17×       13× 13×     13× 13× 13× 13× 13×       13×       13× 13× 13×   13×                   16×   14×                               14×                                                                         13×   11×                 11×                                                         12×   10×                 10×   11×                                                       12×   10×                         10×                           10×                                                         15×   13×       13×                                       10×                                                                               54× 54× 54×   50×   13× 13× 13×     30× 30× 30× 30×   30×               181489×                                      
/* istanbul ignore next */ 
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
/* istanbul ignore next */ 
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
define(["require", "exports", "@syncfusion/ej2-interactive-chat", "../common/index", "../common/index", "../common/index", "../../workbook/common/event", "../../workbook/index", "../../workbook/common/index", "@syncfusion/ej2-base"], function (require, exports, ej2_interactive_chat_1, index_1, index_2, index_3, event_1, index_4, index_5, ej2_base_1) {
    "use strict";
    var _this = this;
    Object.defineProperty(exports, "__esModule", { value: true });
    var AIAssist = (function () {
        function AIAssist(parent) {
            this.currentPrompt = '';
            this.currentPanelWidth = 328;
            this.isAIPanelResized = false;
            this.storedPrompts = [];
            this.isAIPaneVisible = false;
            this.parent = parent;
            this.addEventListener();
        }
        AIAssist.prototype.addEventListener = function () {
            this.parent.on(index_1.showAIAssistPane, this.showAIAssistPane, this);
            this.parent.on(index_1.executePrompt, this.executePromptHandler, this);
        };
        AIAssist.prototype.removeEventListener = function () {
            if (!this.parent.isDestroyed) {
                this.parent.off(index_1.showAIAssistPane, this.showAIAssistPane);
                this.parent.off(index_1.executePrompt, this.executePromptHandler);
            }
        };
        AIAssist.prototype.showAIAssistPane = function (args) {
            this.parent.notify(index_2.renderSidePanel, { show: args.show });
            if (!args.show) {
                this.hideAIAssistPane();
            }
            else {
                this.updatePaneWidth(true);
                var sidePanel = this.parent.element.querySelector("#" + this.parent.element.id + "_ai-assist_panel");
                Eif (sidePanel) {
                    sidePanel.style.width = this.currentPanelWidth + "px";
                    sidePanel.innerHTML = '';
                    this.assistHost = sidePanel;
                    var resizeHandle = this.parent.createElement('div', {
                        id: this.parent.element.id + "_ai_assist_resize",
                        className: 'e-ai-assist-resize-handle'
                    });
                    this.bindResizeEvents(resizeHandle);
                    this.assistHost.appendChild(resizeHandle);
                    this.assistPanel = this.parent.createElement('div', {
                        id: this.parent.element.id + "_ai-assistview_panel",
                        className: 'e-ai-assistview-panel'
                    });
                    this.assistHost.appendChild(this.assistPanel);
                    if (ej2_base_1.isNullOrUndefined(this.aiAssistView)) {
                        this.renderAssistView();
                    }
                    else Eif (this.aiAssistView && this.aiAssistView.element &&
                        this.aiAssistView.element.parentElement !== this.assistPanel) {
                        this.assistPanel.appendChild(this.aiAssistView.element);
                        this.aiAssistView.scrollToBottom();
                    }
                    this.focusAssistTextarea();
                    this.syncRibbonAiButtonState(true);
                    this.isAIPaneVisible = args.show;
                }
            }
        };
        AIAssist.prototype.hideAIAssistPane = function () {
            this.updatePaneWidth(false);
            var sidePanel = this.parent.element.querySelector("#" + this.parent.element.id + "_ai-assist_panel");
            Eif (sidePanel && sidePanel.parentElement) {
                sidePanel.parentElement.removeChild(sidePanel);
            }
            this.syncRibbonAiButtonState(false);
            this.isAIPaneVisible = false;
        };
        AIAssist.prototype.updatePaneWidth = function (show) {
            Iif (this.isAIPanelResized) {
                var host = this.parent.element;
                var id = host.id;
                var sheetEl = show ? host.querySelector('.e-sheet-with-ai-assist-panel') :
                    host.querySelector("#" + id + "_sheet");
                var sheetTabPanel = show ? host.querySelector('.e-sheet-panel-with-ai-assist-panel') :
                    host.querySelector("#" + id + "_sheet_tab_panel");
                sheetEl.style.width = show ? "calc(100% - " + this.currentPanelWidth + "px)" : '';
                sheetTabPanel.style.width = show ? "calc(100% - " + this.currentPanelWidth + "px)" : '';
            }
        };
        AIAssist.prototype.syncRibbonAiButtonState = function (isVisible) {
            var aiBtn = this.parent.element.querySelector("#" + this.parent.element.id + "_aibtn");
            Eif (aiBtn) {
                if (isVisible) {
                    aiBtn.classList.add('e-active');
                }
                else {
                    aiBtn.classList.remove('e-active');
                }
            }
        };
        AIAssist.prototype.bindResizeEvents = function (handle) {
            var _this = this;
            var startX = 0;
            var startWidth = 0;
            var onMouseMove = function (e) {
                var isRtl = _this.parent.enableRtl;
                var delta = isRtl ? (e.clientX - startX) : (startX - e.clientX);
                var newWidth = startWidth + delta;
                newWidth = Math.max(328, Math.min(656, newWidth));
                _this.currentPanelWidth = newWidth;
                _this.assistHost.style.width = newWidth + "px";
                var host = _this.parent.element;
                var sheetEl = host.querySelector('.e-sheet-with-ai-assist-panel');
                var sheetTabPanel = host.querySelector('.e-sheet-panel-with-ai-assist-panel');
                Eif (sheetEl) {
                    sheetEl.style.width = "calc(100% - " + newWidth + "px)";
                }
                Eif (sheetTabPanel) {
                    sheetTabPanel.style.width = "calc(100% - " + newWidth + "px)";
                }
                _this.isAIPanelResized = true;
            };
            var onMouseUp = function () {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
                document.body.style.cursor = '';
                document.body.style.userSelect = '';
            };
            handle.addEventListener('mousedown', function (e) {
                e.preventDefault();
                startX = e.clientX;
                startWidth = _this.assistHost.offsetWidth || _this.currentPanelWidth;
                document.body.style.cursor = 'ew-resize';
                document.body.style.userSelect = 'none';
                document.addEventListener('mousemove', onMouseMove);
                document.addEventListener('mouseup', onMouseUp);
            });
        };
        AIAssist.prototype.focusAssistTextarea = function () {
            var textarea = this.assistPanel && this.assistPanel.querySelector('.e-assist-textarea');
            Eif (textarea) {
                index_3.focus(textarea);
            }
        };
        AIAssist.prototype.renderAssistView = function () {
            var _this = this;
            var l10n = this.parent.serviceLocator.getService(index_3.locale);
            var bannerTemplate = function () {
                var bannerContainer = _this.parent.createElement('div', { className: 'e-banner-container' });
                var icon = _this.parent.createElement('div', { className: 'e-icons e-assistview-icon' });
                var header = _this.parent.createElement('div', { className: 'e-banner-header' });
                header.textContent = l10n.getConstant('AIAssistBannerHeader');
                var content = _this.parent.createElement('div', { className: 'e-banner-content' });
                content.textContent = l10n.getConstant('AIAssistBannerContent');
                bannerContainer.appendChild(icon);
                bannerContainer.appendChild(header);
                bannerContainer.appendChild(content);
                return [bannerContainer];
            };
            var options = {
                views: [{ type: 'Assist', name: l10n.getConstant('AIAssistHeader') }],
                enableRtl: this.parent.enableRtl,
                prompts: this.storedPrompts.length > 0 ? this.storedPrompts : [],
                promptPlaceholder: l10n.getConstant('AIAssistInputPlaceHolder'),
                bannerTemplate: bannerTemplate,
                promptRequest: this.onPromptRequest.bind(this),
                toolbarSettings: {
                    items: [{ iconCss: 'e-icons e-refresh', align: 'Right' }, { iconCss: 'e-icons e-close', align: 'Right' }],
                    itemClicked: this.toolbarItemClicked.bind(this)
                }
            };
            Eif (this.parent.aiAssistSettings) {
                if (this.parent.aiAssistSettings.promptSuggestions && this.storedPrompts.length === 0) {
                    options.promptSuggestions = this.parent.aiAssistSettings.promptSuggestions;
                }
                if (this.parent.aiAssistSettings.placeholder) {
                    options.promptPlaceholder = this.parent.aiAssistSettings.placeholder;
                }
            }
            this.aiAssistView = new ej2_interactive_chat_1.AIAssistView(options);
            this.aiAssistView.createElement = this.parent.createElement;
            this.aiAssistView.isInternalTemplate = true;
            this.aiAssistView.appendTo(this.assistPanel);
            Eif (this.aiAssistView.element) {
                this.aiAssistView.element.addEventListener('click', function () {
                    _this.focusAssistTextarea();
                });
            }
        };
        AIAssist.prototype.toolbarItemClicked = function (args) {
            if (args.item.iconCss === 'e-icons e-refresh') {
                this.aiAssistView.prompts = [];
                this.storedPrompts = [];
                Iif (this.parent.aiAssistSettings.promptSuggestions) {
                    this.aiAssistView.promptSuggestions = this.parent.aiAssistSettings.promptSuggestions;
                }
            }
            if (args.item.iconCss === 'e-icons e-close') {
                this.showAIAssistPane({ show: false });
            }
        };
        AIAssist.prototype.onPromptRequest = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var prompt, command, error_1;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            prompt = args.prompt.trim();
                            Iif (!prompt) {
                                return [2];
                            }
                            this.currentPrompt = prompt;
                            _a.label = 1;
                        case 1:
                            _a.trys.push([1, 4, , 5]);
                            return [4, this.requestAssistCommand(prompt)];
                        case 2:
                            command = _a.sent();
                            return [4, this.executeCommand(command)];
                        case 3:
                            _a.sent();
                            this.aiAssistView.promptSuggestions = [];
                            return [3, 5];
                        case 4:
                            error_1 = _a.sent();
                            this.appendResponse('Unable to process the request.', false);
                            return [3, 5];
                        case 5: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.executePromptHandler = function (args) {
            return __awaiter(this, void 0, void 0, function () {
                var prompt, promptModel, command, responseText, error_2;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            prompt = args.prompt.trim();
                            this.currentPrompt = prompt;
                            Eif (!(this.aiAssistView && !this.aiAssistView.isDestroyed)) return [3, 1];
                            this.aiAssistView.executePrompt(prompt);
                            return [3, 6];
                        case 1:
                            promptModel = { prompt: prompt };
                            this.storedPrompts = this.storedPrompts.concat([promptModel]);
                            _a.label = 2;
                        case 2:
                            _a.trys.push([2, 5, , 6]);
                            return [4, this.requestAssistCommand(prompt)];
                        case 3:
                            command = _a.sent();
                            return [4, this.executeCommand(command)];
                        case 4:
                            responseText = _a.sent();
                            Eif (responseText && this.storedPrompts && this.storedPrompts[this.storedPrompts.length - 1]) {
                                this.storedPrompts[this.storedPrompts.length - 1].response = responseText;
                            }
                            return [3, 6];
                        case 5:
                            error_2 = _a.sent();
                            if (this.storedPrompts && this.storedPrompts[this.storedPrompts.length - 1]) {
                                this.storedPrompts[this.storedPrompts.length - 1].response = 'Unable to process the request.';
                            }
                            return [3, 6];
                        case 6: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.requestAssistCommand = function (prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var actions, error_3;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            _a.trys.push([0, 3, , 4]);
                            return [4, this.requestActionList(prompt)];
                        case 1:
                            actions = _a.sent();
                            Eif (!actions || actions.length === 0) {
                                return [2, [{ action: 'unknown' }]];
                            }
                            return [4, this.requestCommandsForActions(actions, prompt)];
                        case 2: return [2, _a.sent()];
                        case 3:
                            error_3 = _a.sent();
                            return [2, [{ action: 'unknown', message: error_3.message }]];
                        case 4: return [2];
                    }
                });
            });
        };
        AIAssist.prototype.requestActionList = function (prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var request, response, cleaned, parsed;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            request = 'You are a spreadsheet assistant. Identify which actions are needed to fulfill the user request. ' +
                                'Return ONLY a valid JSON array of action name strings. No explanation, no extra text. ' +
                                '\n\nAvailable actions: analysis, query, reportGeneration, edit, findAndReplace, numberFormat, cellFormat, ' +
                                'conditionalFormat, merge, wrap, cut, copy, paste, chart, dataValidation, filter, sort, insert, ' +
                                'delete, autofill, freezePanes, hyperlink, save, unknown' +
                                '\n\nRules:' +
                                '\n- Return ["analysis"] for open-ended analysis or insight requests.' +
                                '\n- Return ["query"] for requests asking about specific data values, details from the current sheet. Only if the question can be answered from the loaded sheet data.' +
                                '\n- Return ["unknown"] if the question is about data not in the sheet, unrelated topics, or no action applies.' +
                                '\n- Insert and delete actions supports only for rows and columns.' +
                                '\n- Multiple actions are allowed e.g. ["edit", "cell_format"].' +
                                '\n- Return valid JSON array only.' +
                                ("\n\nUser request: " + prompt);
                            return [4, serverAIRequest(this.parent, { messages: [{ role: 'user', content: request }] })];
                        case 1:
                            response = _a.sent();
                            Eif (typeof response === 'string' && response.trim()) {
                                try {
                                    cleaned = response.trim()
                                        .replace(/^```json\s*/i, '').replace(/^```\s*/i, '').replace(/\s*```$/, '');
                                    parsed = JSON.parse(cleaned);
                                    if (Array.isArray(parsed)) {
                                        return [2, parsed];
                                    }
                                }
                                catch (_b) {
                                    throw new Error(response);
                                }
                            }
                            return [2, ['unknown']];
                    }
                });
            });
        };
        AIAssist.prototype.requestCommandsForActions = function (actions, prompt) {
            return __awaiter(this, void 0, void 0, function () {
                var combinedSchema, sheetData, request, response, cleaned, parsed;
                var _this = this;
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            combinedSchema = actions.map(function (a) { return a + ": " + _this.getActionSchema(a); }).join('\n\n');
                            sheetData = index_1.getSheetProperties(this.parent, ['rows', 'cells'], this.parent.activeSheetIndex, ['value']);
                            request = 'You are a spreadsheet command parser. ' +
                                'Return a JSON array of command objects — one per action needed. ' +
                                ("\n\nACTION SCHEMAS (populate \"args\" exactly as described):\n" + combinedSchema) +
                                '\n\nCOMMAND FORMAT:' +
                                '\nReturn a JSON array: [{ "action": "<action>", "args": { ... } }, ...]' +
                                '\nDo NOT wrap in any object. Return ONLY the JSON array.' +
                                '\n\nRules:' +
                                '\n- For analysis analyze the current spreadsheet sheet data in detail. Identify key patterns, trends, and inconsistencies in the data; summarize important formulas and their purpose; highlight potential issues such as errors, redundant calculations, broken references, performance bottlenecks, or data quality gaps; and provide clear, actionable recommendations for optimization or improvement. Keep the summary not too long, structured, and business - relevant and append the report message ' +
                                '\n- For query: Answer only from current sheet data. Detect format keywords (table, list, markdown) and respond accordingly in that format. Be direct, concise, factual, deterministic—no invented data. Return unknown if unanswerable.' +
                                '\n- For reportGeneration: base conclusions strictly on provided sheet data — do not invent values. Keep each section concise (prefer bullets). Include up to 5 topRows. For KPIs include a short formula when possible (e.g. "SUM(A2:A100)"). Visual suggestions must include chartType, a valid bounded A1 range, and a one-sentence reason. Do NOT include executable commands or UI actions in the report.' +
                                '\n- Use A1, A1:B11, or "Selected" for range references.' +
                                '\n- If the user does not mention a specific range, omit the range field entirely — except for chart and autofill which must always have a precise bounded range derived from the sheet data (e.g. "A1:C12"). Never use open-ended references like "A:A", "1:1", or "B:B" under any circumstance.' +
                                '\n- If you cannot map to any action, return {"action":"unknown","message":"<explanation>"}. ' +
                                '\n- Preserve formulas with "=" prefix.' +
                                '\n- Do not invent missing details.' +
                                '\n- Return valid JSON only.' +
                                ("\n\nCurrent sheet data: " + sheetData) +
                                ("\n\nUser request: " + prompt);
                            return [4, serverAIRequest(this.parent, { messages: [{ role: 'user', content: request }] })];
                        case 1:
                            response = _a.sent();
                            Eif (typeof response === 'string' && response.trim()) {
                                try {
                                    cleaned = response.trim()
                                        .replace(/^```json\s*/i, '').replace(/^```\s*/i, '').replace(/\s*```$/, '');
                                    parsed = JSON.parse(cleaned);
                                    Eif (Array.isArray(parsed)) {
                                        return [2, parsed];
                                    }
                                }
                                catch (_b) {
                                    return [2, [{ action: 'unknown', message: response }]];
                                }
                            }
                            return [2, [{ action: 'unknown' }]];
                    }
                });
            });
        };
        AIAssist.prototype.getActionSchema = function (action) {
            var schemas = {
                analysis: '{ message: string }',
                query: '{ message: string }',
                reportGeneration: '{ reportStructure: {' +
                    '  summary: string,' +
                    '  sections: [{ heading: string, content: string }],' +
                    '  kpis: [{ name: string, value: string, formula?: string }],' +
                    '  topRows: [{ row: number, values: { [header: string]: string|number } }],' +
                    '  visualSuggestions: [{ chartType: string, range: string, reason: string }]' +
                    '} }',
                edit: '{ address: string, value: string (preserve "=" prefix for formulas) }',
                findAndReplace: '{ findValue: string, replaceValue: string, caseSensitive?: boolean (default false), exactMatch?: boolean (default false) }',
                numberFormat: '{ range: string, format: General|Number|Currency|Accounting|ShortDate|LongDate|Time|Percentage|Fraction|Scientific|Text }',
                cellFormat: '{ range: string, formatting: { bold?: boolean, italic?: boolean, underline?: boolean, strikethrough?: boolean, fontSize?: number, fontFamily?: string, color?: string (hex), backgroundColor?: string (hex) } }',
                conditionalFormat: '{ range: string, type: GreaterThan|LessThan|Between|EqualTo|ContainsText|DateOccur|Duplicate|Unique|Top10Items|Bottom10Items|Top10Percentage|Bottom10Percentage|AboveAverage|BelowAverage, value: string (for Between use "min,max"), cFColor: RedFT|YellowFT|GreenFT }',
                merge: '{ range: string, direction: "All"|"Vertically"|"Horizontally" (default "All") }',
                wrap: '{ range: string, wrap: boolean }',
                cut: '{ range: string }',
                copy: '{ range: string }',
                paste: '{ range: string }',
                chart: '{ range: string, chartType: Column|Bar|Line|Area|Pie|Doughnut|Scatter|StackingColumn|StackingColumn100|StackingBar|StackingBar100|StackingLine|StackingLine100|StackingArea|StackingArea100, theme?: Material|Bootstrap|Fabric|Office365|Tailwind, title?: string, isSeriesInRows?: boolean, height?: number, width?: number }',
                dataValidation: '{ range: string, dvType: WholeNumber|Decimal|Date|Time|TextLength|List|Custom, dvOperator?: Between|NotBetween|EqualTo|NotEqualTo|GreaterThan|LessThan|GreaterThanOrEqualTo|LessThanOrEqualTo, dvValue1?: string, dvValue2?: string, dvIgnoreBlank?: boolean, dvInCellDropDown?: boolean, isHighlighted?: boolean }',
                filter: '{ range: string, filterColumn: string (column letter e.g. "A"), ' +
                    'filterOperator: equal|notequal|greaterthan|lessthan|greaterthanorequal|lessthanorequal|contains|startswith|endswith|isempty|isnotempty, ' +
                    'filterValue: string, clearFilter?: boolean (true to remove filter) }',
                sort: '{ range?: string (omit if user does not mention a specific range), ' +
                    'sortColumn?: string (column letter e.g. "A", omit if not specified — first column of range will be used), ' +
                    'sortOrder: "Ascending"|"Descending" (default "Ascending"), ' +
                    'sortContainsHeader?: boolean (default true) }',
                insert: '{ modelType: "Row"|"Column", startIndex: number (1-based row or column number), ' +
                    'count?: number (number of rows/columns to insert, default 1) }',
                delete: '{ modelType: "Row"|"Column", startIndex: number (1-based row or column number), ' +
                    'count?: number (number of rows/columns to delete, default 1) }',
                autofill: '{ dataRange: string (source range e.g. "A1:A3"), fillRange: string (target range to fill e.g. "A4:A10"), ' +
                    'direction?: "Down"|"Up"|"Left"|"Right" (auto-detected if omitted), ' +
                    'fillType?: "FillSeries"|"CopyCells"|"FillFormattingOnly"|"FillWithoutFormatting" (default "FillSeries") }',
                freezePanes: '{ freezeType: "Rows"|"Columns"|"Panes"|"Unfreeze", ' +
                    'row?: number (number of rows to freeze, 0 to unfreeze rows, default 0), ' +
                    'column?: number (number of columns to freeze, 0 to unfreeze columns, default 0) }',
                hyperlink: '{ address: string (URL e.g. "https://example.com" or cell/sheet reference e.g. "Sheet1!A1" or defined name), ' +
                    'displayText?: string (text to display in the cell, omit to keep existing), ' +
                    'range?: string (target cell or range, defaults to selected cell) }',
                save: '{ saveType: "xlsx"|"xls"|"csv"|"pdf" (default "xlsx") }'
            };
            return schemas[action];
        };
        AIAssist.prototype.executeCommand = function (commands) {
            return __awaiter(this, void 0, void 0, function () {
                var responses, batchableActions, i, command, response, batchAction, batch, _a, responseText;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            responses = [];
                            batchableActions = new Set(['edit', 'cellFormat', 'numberFormat']);
                            i = 0;
                            _b.label = 1;
                        case 1:
                            if (!(i < commands.length)) return [3, 28];
                            command = commands[i];
                            response = '';
                            if (!batchableActions.has(command.action)) return [3, 2];
                            batchAction = command.action;
                            batch = [];
                            while (i < commands.length && commands[i].action === batchAction) {
                                batch.push(commands[i]);
                                i++;
                            }
                            response = batch.length > 1
                                ? this.applyCommandBatch(batchAction, batch)
                                : this.applyBatchableAction(batchAction, batch[0].args);
                            return [3, 27];
                        case 2:
                            _a = command.action;
                            switch (_a) {
                                case 'analysis': return [3, 3];
                                case 'query': return [3, 4];
                                case 'reportGeneration': return [3, 5];
                                case 'findAndReplace': return [3, 6];
                                case 'conditionalFormat': return [3, 7];
                                case 'merge': return [3, 8];
                                case 'cut': return [3, 9];
                                case 'copy': return [3, 11];
                                case 'paste': return [3, 13];
                                case 'wrap': return [3, 14];
                                case 'chart': return [3, 15];
                                case 'dataValidation': return [3, 16];
                                case 'filter': return [3, 17];
                                case 'sort': return [3, 18];
                                case 'insert': return [3, 19];
                                case 'delete': return [3, 20];
                                case 'autofill': return [3, 21];
                                case 'freezePanes': return [3, 22];
                                case 'hyperlink': return [3, 23];
                                case 'save': return [3, 24];
                            }
                            return [3, 25];
                        case 3:
                            response = command.args.message;
                            return [3, 26];
                        case 4:
                            response = this.formatQueryResponse(command.args.message);
                            return [3, 26];
                        case 5:
                            response = command.args.reportStructure ? this.buildReportNarrative(command.args.reportStructure)
                                : 'Report generation failed: no report structure returned.';
                            return [3, 26];
                        case 6:
                            response = this.applyFindReplace(command.args);
                            return [3, 26];
                        case 7:
                            response = this.applyConditionalFormat(command.args);
                            return [3, 26];
                        case 8:
                            response = this.applyMerge(command.args);
                            return [3, 26];
                        case 9: return [4, this.applyCut(command.args)];
                        case 10:
                            response = _b.sent();
                            return [3, 26];
                        case 11: return [4, this.applyCopy(command.args)];
                        case 12:
                            response = _b.sent();
                            return [3, 26];
                        case 13:
                            response = this.applyPaste(command.args);
                            return [3, 26];
                        case 14:
                            response = this.applyWrap(command.args);
                            return [3, 26];
                        case 15:
                            response = this.applyChart(command.args);
                            return [3, 26];
                        case 16:
                            response = this.applyDataValidation(command.args);
                            return [3, 26];
                        case 17:
                            response = this.applyFilterAction(command.args);
                            return [3, 26];
                        case 18:
                            response = this.applySortAction(command.args);
                            return [3, 26];
                        case 19:
                            response = this.applyInsert(command.args);
                            return [3, 26];
                        case 20:
                            response = this.applyDelete(command.args);
                            return [3, 26];
                        case 21:
                            response = this.applyAutoFill(command.args);
                            return [3, 26];
                        case 22:
                            response = this.applyFreezePanes(command.args);
                            return [3, 26];
                        case 23:
                            response = this.applyHyperlink(command.args);
                            return [3, 26];
                        case 24:
                            response = this.applySave(command.args);
                            return [3, 26];
                        case 25:
                            response = command.message || 'I can analyze the sheet, update values, replace content, or apply number formats.';
                            return [3, 26];
                        case 26:
                            i++;
                            _b.label = 27;
                        case 27:
                            Eif (response) {
                                responses.push(response);
                            }
                            return [3, 1];
                        case 28:
                            responseText = responses.length > 0 ? responses.join('\n\n') : '';
                            Eif (responseText) {
                                this.appendResponse(responseText);
                            }
                            return [2, responseText];
                    }
                });
            });
        };
        AIAssist.prototype.applyBatchableAction = function (action, args) {
            switch (action) {
                case 'edit': return this.applyEdit(args);
                case 'cellFormat': return this.applyCellFormat(args);
                case 'numberFormat': return this.applyNumberFormat(args);
                default: return '';
            }
        };
        AIAssist.prototype.applyCommandBatch = function (action, commands) {
            for (var _i = 0, commands_1 = commands; _i < commands_1.length; _i++) {
                var cmd = commands_1[_i];
                this.applyBatchableAction(action, cmd.args);
            }
            var ranges = commands
                .map(function (cmd) { return cmd.args && (cmd.args.range || cmd.args.address); })
                .filter(function (r) { return !ej2_base_1.isNullOrUndefined(r) && r !== ''; });
            var rangeText = ranges.length > 0 ? ranges.join(', ') : 'selected cells';
            switch (action) {
                case 'edit': {
                    var addresses = commands
                        .map(function (cmd) { return cmd.args && cmd.args.address; })
                        .filter(function (a) { return !ej2_base_1.isNullOrUndefined(a) && a !== ''; });
                    var uniqueValues = Array.from(new Set(commands.map(function (cmd) { return cmd.args && cmd.args.value; })));
                    var compactRange = addresses.length > 0
                        ? this.buildAddressRangeText(addresses) : 'selected cells';
                    var valueText = uniqueValues.length === 1
                        ? "" + uniqueValues[0] : commands.length + " different values";
                    return "Updated cell range " + compactRange + " with " + valueText + ".";
                }
                case 'cellFormat':
                    return "Applied cell formatting across " + commands.length + " range(s): " + rangeText + ".";
                case 'numberFormat': {
                    var formats = Array.from(new Set(commands.map(function (cmd) { return cmd.args && cmd.args.format; }).filter(Boolean)));
                    var formatText = formats.length === 1 ? formats[0] : 'multiple formats';
                    return "Applied " + formatText + " number format to " + commands.length + " range(s): " + rangeText + ".";
                }
                default:
                    return "Applied " + action + " to " + commands.length + " range(s): " + rangeText + ".";
            }
        };
        AIAssist.prototype.buildAddressRangeText = function (addresses) {
            if (addresses.length === 0) {
                return '';
            }
            if (addresses.length === 1) {
                return addresses[0];
            }
            try {
                var indices = addresses.map(function (a) { return index_5.getRangeIndexes(a); });
                var minRow = Math.min.apply(Math, indices.map(function (idx) { return idx[0]; }));
                var minCol = Math.min.apply(Math, indices.map(function (idx) { return idx[1]; }));
                var maxRow = Math.max.apply(Math, indices.map(function (idx) { return idx[2] !== undefined ? idx[2] : idx[0]; }));
                var maxCol = Math.max.apply(Math, indices.map(function (idx) { return idx[3] !== undefined ? idx[3] : idx[1]; }));
                var startCell = "" + index_5.getColumnHeaderText(minCol + 1) + (minRow + 1);
                var endCell = "" + index_5.getColumnHeaderText(maxCol + 1) + (maxRow + 1);
                return startCell === endCell ? startCell : startCell + ":" + endCell;
            }
            catch (_a) {
                return addresses[0] + ":" + addresses[addresses.length - 1];
            }
        };
        AIAssist.prototype.formatQueryResponse = function (message) {
            if (typeof message === 'string') {
                return message;
            }
            return JSON.stringify(message);
        };
        AIAssist.prototype.buildReportNarrative = function (report) {
            Iif (typeof report === 'string') {
                try {
                    report = JSON.parse(report);
                }
                catch (_a) {
                    return 'Report generation failed: invalid report structure format.';
                }
            }
            var escapeCell = function (s) {
                Iif (s === null || s === undefined) {
                    return '';
                }
                return ("" + s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
            };
            var narrative = '**Report Summary**\n\n';
            Eif (report.summary) {
                narrative += report.summary + "\n\n";
            }
            if (report.kpis && report.kpis.length > 0) {
                narrative += '**Key KPIs:**\n';
                report.kpis.forEach(function (kpi) {
                    narrative += "- " + kpi.name + ": " + kpi.value + (kpi.formula ? " (formula: " + kpi.formula + ")" : '') + '\n';
                });
                narrative += '\n';
            }
            if (report.topRows && report.topRows.length > 0) {
                var rows = report.topRows.slice(0, 5);
                var firstValues = (rows[0] && rows[0].values);
                var headers_1 = Object.keys(firstValues);
                Eif (headers_1.length > 0) {
                    narrative += '**Top Rows (sample):**\n\n';
                    narrative += "| " + headers_1.map(function (h) { return escapeCell(h); }).join(' | ') + " |\n";
                    narrative += "| " + headers_1.map(function () { return '---'; }).join(' | ') + " |\n";
                    rows.forEach(function (r) {
                        var vals = headers_1.map(function (h) {
                            return escapeCell((r.values && r.values[h] !== undefined)
                                ? r.values[h] : '');
                        });
                        narrative += "| " + vals.join(' | ') + " |\n";
                    });
                    narrative += '\n';
                }
            }
            if (report.visualSuggestions && report.visualSuggestions.length > 0) {
                narrative += '**Visual Suggestions:**\n';
                report.visualSuggestions.forEach(function (v) {
                    narrative += "- " + v.chartType + ": range " + v.range + (v.reason ? " \u2014 " + v.reason : '') + '\n';
                });
                narrative += '\n';
            }
            Eif (report.sections && report.sections.length > 0) {
                report.sections.forEach(function (section) {
                    narrative += "**" + section.heading + "**\n" + section.content + "\n\n";
                });
            }
            if (report.kpis && report.kpis.some(function (k) {
                return k.formula && k.formula.length > 0;
            })) {
                narrative += '**Suggested Formulas:**\n';
                report.kpis.forEach(function (k) {
                    Eif (k.formula) {
                        narrative += "- " + k.name + ": " + k.formula + "\n";
                    }
                });
                narrative += '\n';
            }
            return narrative.trim();
        };
        AIAssist.prototype.applyEdit = function (data) {
            var address = this.getTargetAddress(data && (data.address));
            var value = data.value;
            var sheetName = this.parent.getActiveSheet().name;
            var eventArgs = { address: sheetName + "!" + address, value: value };
            this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'cellSave' });
            this.parent.notify(event_1.workbookEditOperation, {
                action: 'updateCellValue',
                address: address,
                value: value,
                sheetIndex: this.parent.activeSheetIndex
            });
            var range = index_5.getRangeIndexes(address);
            var cellRenderer = this.parent.serviceLocator.getService('cell');
            cellRenderer.refresh(range[0], range[1], true, null, true);
            this.parent.notify(index_1.completeAction, { eventArgs: eventArgs, action: 'cellSave' });
            return "Updated " + address + " to " + value + ".";
        };
        AIAssist.prototype.applyFindReplace = function (data) {
            Iif (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.findValue) || ej2_base_1.isNullOrUndefined(data.replaceValue)) {
                return 'Please provide both the value to replace and the replacement value.';
            }
            var findOptions = {
                value: (data.findValue).toString(),
                replaceValue: (data.replaceValue).toString(),
                mode: 'Sheet',
                sheetIndex: this.parent.activeSheetIndex,
                isCSen: data.caseSensitive === true,
                isEMatch: data.exactMatch === true,
                searchBy: 'By Row',
                isAction: true
            };
            this.parent.notify(event_1.replaceAll, findOptions);
            var caseInfo = data.caseSensitive === true ? ' (case-sensitive)' : '';
            var matchInfo = data.exactMatch === true ? ' with exact match' : '';
            return "Replaced all occurrences of \"" + data.findValue + "\" with \"" + data.replaceValue + "\"" + caseInfo + matchInfo + ".";
        };
        AIAssist.prototype.applyNumberFormat = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.format)) {
                return 'Please provide a number format pattern.';
            }
            var range = this.getTargetRange(data.range);
            var sheetName = this.parent.getActiveSheet().name;
            var eventArgs = {
                format: index_4.getFormatFromType(data.format),
                range: range, cancel: false
            };
            var actionArgs = {
                range: sheetName + '!' + range, format: index_4.getFormatFromType(data.format), requestType: 'NumberFormat'
            };
            var isReadonly = index_5.isReadOnlyCells(this.parent, index_5.getSwapRange(index_5.getRangeIndexes(eventArgs.range)));
            Eif (!isReadonly) {
                this.parent.trigger('beforeCellFormat', eventArgs);
                this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'format' });
                Iif (eventArgs.cancel) {
                    return '';
                }
            }
            this.parent.notify(index_5.applyNumberFormatting, eventArgs);
            this.parent.notify(index_5.selectionComplete, { type: 'mousedown' });
            Eif (!isReadonly) {
                this.parent.notify(index_1.completeAction, { eventArgs: actionArgs, action: 'format' });
            }
            return "Applied number format " + data.format + " to " + range + ".";
        };
        AIAssist.prototype.applyCellFormat = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.formatting) || Object.keys(data.formatting).length === 0) {
                return 'Please provide style properties to apply.';
            }
            var range = this.getTargetRange(data.range);
            var sheetName = this.parent.getActiveSheet().name;
            var src = data.formatting;
            var style = {};
            if (src.bold !== undefined) {
                style.fontWeight = src.bold === true ? 'bold' : 'normal';
            }
            if (src.italic !== undefined) {
                style.fontStyle = src.italic === true ? 'italic' : 'normal';
            }
            var hasUnderline = src.underline === true;
            var hasStrike = src.strikethrough === true;
            if (hasUnderline || hasStrike) {
                style.textDecoration = hasUnderline && hasStrike ? 'underline line-through' : (hasUnderline ? 'underline' : 'line-through');
            }
            if (src.fontSize !== undefined) {
                var fs = src.fontSize;
                if (typeof fs === 'number') {
                    style.fontSize = fs + "pt";
                }
                else if (typeof fs === 'string' && /^\d+$/.test(fs)) {
                    style.fontSize = fs + "pt";
                }
                else {
                    style.fontSize = fs;
                }
            }
            if (src.fontFamily) {
                style.fontFamily = src.fontFamily;
            }
            if (src.color) {
                style.color = src.color;
            }
            if (src.backgroundColor) {
                style.backgroundColor = src.backgroundColor;
            }
            Object.keys(src).forEach(function (k) {
                Iif (['bold', 'italic', 'underline', 'strikethrough', 'fontSize', 'fontFamily', 'color', 'backgroundColor'].indexOf(k) === -1) {
                    style[k] = src[k];
                }
            });
            var eventArgs = { style: style, range: sheetName + '!' + range, cancel: false, requestType: 'CellFormat' };
            var actionArgs = {
                range: sheetName + '!' + range, style: style, requestType: 'CellFormat'
            };
            var isReadonly = index_5.isReadOnlyCells(this.parent, index_5.getSwapRange(index_5.getRangeIndexes(eventArgs.range)));
            Eif (!isReadonly) {
                this.parent.trigger('beforeCellFormat', eventArgs);
                this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'format' });
                Iif (eventArgs.cancel) {
                    return '';
                }
            }
            this.parent.notify(index_5.setCellFormat, {
                range: actionArgs.range, style: style,
                onActionUpdate: true, refreshRibbon: true
            });
            this.parent.notify(index_5.selectionComplete, { type: 'mousedown' });
            Eif (!isReadonly) {
                this.parent.notify(index_1.completeAction, { eventArgs: actionArgs, action: 'format' });
            }
            return "Applied cell style to " + range + ".";
        };
        AIAssist.prototype.applyConditionalFormat = function (data) {
            if (ej2_base_1.isNullOrUndefined(data)) {
                return 'Please provide conditional format details.';
            }
            var range = this.getTargetRange(data.range);
            var cfModel = {
                range: range,
                type: this.normalizeCFType(data.type),
                value: !ej2_base_1.isNullOrUndefined(data.value) ? String(data.value) : undefined,
                cFColor: this.normalizeCFColor(data.cFColor),
                format: data.format
            };
            var args = { cfModel: cfModel, isAction: true };
            this.parent.notify(event_1.setCFRule, args);
            return "Applied conditional format (" + cfModel.type + ") to " + range + ".";
        };
        AIAssist.prototype.normalizeCFType = function (type) {
            if (ej2_base_1.isNullOrUndefined(type) || type === '') {
                return 'GreaterThan';
            }
            var map = {
                'greaterthan': 'GreaterThan', 'greater': 'GreaterThan', 'gt': 'GreaterThan',
                'lessthan': 'LessThan', 'less': 'LessThan', 'lt': 'LessThan',
                'between': 'Between',
                'equalto': 'EqualTo', 'equal': 'EqualTo', 'eq': 'EqualTo',
                'containstext': 'ContainsText', 'contains': 'ContainsText',
                'dateoccur': 'DateOccur', 'date': 'DateOccur',
                'duplicate': 'Duplicate',
                'unique': 'Unique',
                'top10items': 'Top10Items', 'top10': 'Top10Items',
                'bottom10items': 'Bottom10Items', 'bottom10': 'Bottom10Items',
                'top10percentage': 'Top10Percentage', 'toppercent': 'Top10Percentage',
                'bottom10percentage': 'Bottom10Percentage', 'bottompercent': 'Bottom10Percentage',
                'aboveaverage': 'AboveAverage', 'above': 'AboveAverage',
                'belowaverage': 'BelowAverage', 'below': 'BelowAverage'
            };
            return map[type.toLowerCase().replace(/\s/g, '')] || 'GreaterThan';
        };
        AIAssist.prototype.normalizeCFColor = function (color) {
            if (ej2_base_1.isNullOrUndefined(color) || color === '') {
                return 'RedFT';
            }
            var map = {
                'redft': 'RedFT', 'lightredfillwithdarkredtext': 'RedFT', 'red': 'RedFT',
                'yellowft': 'YellowFT', 'yellowfillwithdarkyellowtext': 'YellowFT', 'yellow': 'YellowFT',
                'greenft': 'GreenFT', 'greenfillwithdarkgreentext': 'GreenFT', 'green': 'GreenFT',
                'redf': 'RedF', 'redfill': 'RedFT'
            };
            return map[color.toLowerCase().replace(/\s/g, '')] || 'RedFT';
        };
        AIAssist.prototype.applyMerge = function (data) {
            if (ej2_base_1.isNullOrUndefined(data)) {
                return 'Please provide merge range or address.';
            }
            var range = this.getTargetRange(data.range);
            var mergeType = data.direction;
            var args = { range: range, type: mergeType, merge: true, isAction: true, refreshRibbon: true };
            this.parent.notify(event_1.setMerge, args);
            return "Merged " + range + " as " + mergeType + ".";
        };
        AIAssist.prototype.applyCut = function (data) {
            return __awaiter(this, void 0, void 0, function () {
                var rangeStr, indices;
                return __generator(this, function (_a) {
                    if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.range)) {
                        return [2, 'Please provide a range to cut.'];
                    }
                    rangeStr = this.getTargetRange(data.range);
                    indices = index_5.getSwapRange(index_5.getRangeIndexes(rangeStr));
                    this.parent.notify(index_2.cut, { range: indices, sId: this.parent.getActiveSheet().id, invokeCopy: true });
                    return [2, "Cut " + rangeStr + ". Use paste to place it at the target location."];
                });
            });
        };
        AIAssist.prototype.applyCopy = function (data) {
            return __awaiter(this, void 0, void 0, function () {
                var rangeStr, indices;
                return __generator(this, function (_a) {
                    if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.range)) {
                        return [2, 'Please provide a range to copy.'];
                    }
                    rangeStr = this.getTargetRange(data.range);
                    indices = index_5.getSwapRange(index_5.getRangeIndexes(rangeStr));
                    this.parent.notify(index_1.copy, { range: indices, sId: this.parent.getActiveSheet().id, invokeCopy: true });
                    return [2, "Copied " + rangeStr + "."];
                });
            });
        };
        AIAssist.prototype.applyPaste = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.range)) {
                return 'Please provide a paste target address.';
            }
            var rangeStr = this.getTargetRange(data.range);
            var indices = index_5.getSwapRange(index_5.getRangeIndexes(rangeStr));
            var sheetIndex = this.parent.activeSheetIndex;
            this.parent.notify(index_1.paste, { range: indices, sIdx: sheetIndex, isAction: true, isInternal: true });
            return "Pasted into " + rangeStr + ".";
        };
        AIAssist.prototype.applyWrap = function (data) {
            var address = this.getTargetRange(data && (data.range));
            var wrapFlag = data.wrap;
            var sheetName = this.parent.getActiveSheet().name;
            var range = address;
            var eventArgs = { address: sheetName + "!" + range, wrap: wrapFlag, cancel: false };
            Iif (index_5.isReadOnlyCells(this.parent, index_5.getSwapRange(index_5.getRangeIndexes(range)))) {
                return 'Cannot change wrap on read-only range.';
            }
            this.parent.notify(event_1.beginAction, { action: 'beforeWrap', eventArgs: eventArgs });
            Iif (eventArgs.cancel) {
                return '';
            }
            index_4.wrap(range, wrapFlag, this.parent);
            this.parent.notify(index_1.completeAction, { action: 'wrap', eventArgs: { address: sheetName + "!" + range, wrap: wrapFlag } });
            return (wrapFlag ? 'Enabled' : 'Disabled') + " wrap for " + address + ".";
        };
        AIAssist.prototype.applyChart = function (data) {
            if (ej2_base_1.isNullOrUndefined(data)) {
                return 'Please provide chart details such as type and range.';
            }
            var range = this.getTargetRange(data.range);
            var sheetName = this.parent.getActiveSheet().name;
            var chartModel = {
                type: this.normalizeChartType(data.chartType),
                range: sheetName + "!" + range,
                theme: data.theme || 'Material',
                title: data.title || '',
                isSeriesInRows: data.isSeriesInRows === true,
                height: data.height || 290,
                width: data.width || 480,
                markerSettings: { visible: false, isFilled: true }
            };
            this.parent.notify(event_1.setChart, { chart: [chartModel] });
            return "Inserted " + chartModel.type + " chart for range " + range + ".";
        };
        AIAssist.prototype.normalizeChartType = function (type) {
            if (ej2_base_1.isNullOrUndefined(type) || type === '') {
                return 'Column';
            }
            var map = {
                'column': 'Column', 'clusteredcolumn': 'Column',
                'stackedcolumn': 'StackingColumn', 'stackedcolumn100': 'StackingColumn100',
                'bar': 'Bar', 'clusteredbar': 'Bar',
                'stackedbar': 'StackingBar', 'stackedbar100': 'StackingBar100',
                'line': 'Line', 'stackedline': 'StackingLine', 'stackedline100': 'StackingLine100',
                'area': 'Area', 'stackedarea': 'StackingArea', 'stackedarea100': 'StackingArea100',
                'pie': 'Pie', 'doughnut': 'Doughnut', 'scatter': 'Scatter'
            };
            return (map[type.toLowerCase().replace(/\s/g, '')] || 'Column');
        };
        AIAssist.prototype.applyDataValidation = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.dvType)) {
                return 'Please provide data validation details (type and range).';
            }
            var range = this.getTargetRange(data.range);
            var sheetName = this.parent.getActiveSheet().name;
            var fullRange = sheetName + '!' + range;
            var eventArgs = {
                range: fullRange,
                value1: data.dvValue1,
                value2: data.dvValue2 || '',
                ignoreBlank: data.dvIgnoreBlank !== false,
                type: this.normalizeDVType(data.dvType),
                operator: this.normalizeDVOperator(data.dvOperator),
                inCellDropDown: data.dvInCellDropDown !== false,
                cancel: false
            };
            var isReadonly = index_5.isReadOnlyCells(this.parent, index_5.getSwapRange(index_5.getRangeIndexes(range)));
            Iif (isReadonly) {
                return 'Cannot apply data validation to a read-only range.';
            }
            this.parent.trigger('beforeCellFormat', eventArgs);
            Iif (eventArgs.cancel) {
                return '';
            }
            this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'validation' });
            this.parent.notify(event_1.cellValidation, {
                rules: {
                    type: eventArgs.type,
                    operator: eventArgs.operator,
                    value1: eventArgs.value1,
                    value2: eventArgs.value2,
                    ignoreBlank: eventArgs.ignoreBlank,
                    inCellDropDown: eventArgs.inCellDropDown,
                    isHighlighted: data.isHighlighted === true
                },
                range: fullRange,
                isAction: true
            });
            this.parent.notify(index_1.completeAction, { eventArgs: eventArgs, action: 'validation' });
            return "Applied " + eventArgs.type + " validation (" + eventArgs.operator + ") to " + range + ".";
        };
        AIAssist.prototype.normalizeDVType = function (type) {
            if (ej2_base_1.isNullOrUndefined(type) || type === '') {
                return 'WholeNumber';
            }
            var map = {
                'whole': 'WholeNumber', 'wholenumber': 'WholeNumber', 'integer': 'WholeNumber',
                'decimal': 'Decimal', 'number': 'Decimal',
                'date': 'Date', 'datetime': 'Date',
                'time': 'Time',
                'textlength': 'TextLength', 'text': 'TextLength',
                'list': 'List', 'dropdown': 'List', 'dropdownlist': 'List',
                'custom': 'Custom', 'formula': 'Custom'
            };
            return map[type.toLowerCase().replace(/\s/g, '')] || 'WholeNumber';
        };
        AIAssist.prototype.normalizeDVOperator = function (op) {
            if (ej2_base_1.isNullOrUndefined(op) || op === '') {
                return 'Between';
            }
            var map = {
                'between': 'Between', 'range': 'Between', 'notbetween': 'NotBetween',
                'equalto': 'EqualTo', 'equals': 'EqualTo', 'equal': 'EqualTo', 'eq': 'EqualTo',
                'notequalto': 'NotEqualTo', 'notequals': 'NotEqualTo', 'notequal': 'NotEqualTo', 'neq': 'NotEqualTo',
                'greaterthan': 'GreaterThan', 'greater': 'GreaterThan', 'gt': 'GreaterThan',
                'lessthan': 'LessThan', 'less': 'LessThan', 'lt': 'LessThan',
                'greaterthanorequal': 'GreaterThanOrEqualTo', 'gte': 'GreaterThanOrEqualTo',
                'lessthanorequal': 'LessThanOrEqualTo', 'lte': 'LessThanOrEqualTo'
            };
            return map[op.toLowerCase().replace(/\s/g, '').replace(/>/g, 'than').replace(/</g, 'than')];
        };
        AIAssist.prototype.applyFilterAction = function (data) {
            if (ej2_base_1.isNullOrUndefined(data)) {
                return 'Please provide filter details such as column and value.';
            }
            var range = this.getTargetRange(data.range);
            var sheetIndex = this.parent.activeSheetIndex;
            if (data.clearFilter === true) {
                this.parent.notify(index_1.initiateFilterUI, { range: range, sIdx: sheetIndex, predicates: [], isInternal: false });
                return "Cleared filter on " + range + ".";
            }
            if (ej2_base_1.isNullOrUndefined(data.filterColumn) || data.filterColumn === '') {
                return 'Please provide a column to filter.';
            }
            var colLetter = data.filterColumn.toUpperCase().replace(/[^A-Z]/g, '');
            var colIndex = index_5.getIndexesFromAddress(colLetter + "1")[1];
            var field = index_5.getColumnHeaderText(colIndex + 1);
            var operator = this.normalizeFilterOperator(data.filterOperator);
            var predicates = [{
                    field: field,
                    operator: operator,
                    value: data.filterValue,
                    matchCase: false,
                    ignoreAccent: false,
                    predicate: 'and',
                    type: 'string'
                }];
            this.parent.notify(index_1.initiateFilterUI, {
                predicates: predicates,
                range: range,
                sIdx: sheetIndex,
                isInternal: false
            });
            return "Applied filter on column " + colLetter + ": " + operator + " \"" + data.filterValue + "\".";
        };
        AIAssist.prototype.normalizeFilterOperator = function (op) {
            if (ej2_base_1.isNullOrUndefined(op) || op === '') {
                return 'equal';
            }
            var map = {
                'equal': 'equal', 'eq': 'equal', 'equals': 'equal',
                'notequal': 'notequal', 'neq': 'notequal', 'notequals': 'notequal',
                'greaterthan': 'greaterthan', 'gt': 'greaterthan', 'greater': 'greaterthan',
                'lessthan': 'lessthan', 'lt': 'lessthan', 'less': 'lessthan',
                'greaterthanorequal': 'greaterthanorequal', 'gte': 'greaterthanorequal',
                'lessthanorequal': 'lessthanorequal', 'lte': 'lessthanorequal',
                'contains': 'contains',
                'startswith': 'startswith', 'beginswith': 'startswith',
                'endswith': 'endswith',
                'isempty': 'isempty', 'empty': 'isempty',
                'isnotempty': 'isnotempty', 'notempty': 'isnotempty'
            };
            return map[op.toLowerCase().replace(/\s/g, '')] || 'equal';
        };
        AIAssist.prototype.applySortAction = function (data) {
            if (ej2_base_1.isNullOrUndefined(data)) {
                return 'Please provide sort details.';
            }
            var sheet = this.parent.getActiveSheet();
            var hasRange = !ej2_base_1.isNullOrUndefined(data.range) && data.range !== '' &&
                data.range.toLowerCase() !== 'selected';
            var range = hasRange ? data.range : undefined;
            var effectiveRange = range || sheet.selectedRange;
            var field;
            if (!ej2_base_1.isNullOrUndefined(data.sortColumn) && data.sortColumn !== '') {
                var colLetter = data.sortColumn.toUpperCase().replace(/[^A-Z]/g, '');
                var colIndex = index_5.getIndexesFromAddress(colLetter + "1")[1];
                field = index_5.getColumnHeaderText(colIndex + 1);
            }
            else {
                var rangeIdx = index_5.getRangeIndexes(effectiveRange);
                field = index_5.getColumnHeaderText(rangeIdx[1] + 1);
            }
            var order = this.normalizeSortOrder(data.sortOrder);
            var containsHeader = data.sortContainsHeader !== false;
            var sortArgs = {
                sortOptions: {
                    sortDescriptors: { field: field, order: order },
                    containsHeader: containsHeader
                }
            };
            if (hasRange) {
                sortArgs.range = range;
            }
            this.parent.notify(index_1.applySort, sortArgs);
            var rangeInfo = hasRange ? " in range " + range : ' in the selected range';
            return "Sorted by column " + field + rangeInfo + " in " + order + " order.";
        };
        AIAssist.prototype.normalizeSortOrder = function (order) {
            if (ej2_base_1.isNullOrUndefined(order) || order === '') {
                return 'Ascending';
            }
            var map = {
                'ascending': 'Ascending', 'asc': 'Ascending', 'a-z': 'Ascending', 'az': 'Ascending',
                'descending': 'Descending', 'desc': 'Descending', 'z-a': 'Descending', 'za': 'Descending'
            };
            return map[order.toLowerCase().replace(/\s/g, '')];
        };
        AIAssist.prototype.applyInsert = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.modelType)) {
                return 'Please provide modelType (Row or Column) and startIndex.';
            }
            var type = this.normalizeModelType(data.modelType);
            if (!type) {
                return 'Invalid modelType. Please specify "Row" or "Column".';
            }
            var startIdx = Math.max(0, data.startIndex - 1);
            var count = Math.max(1, data.count);
            var endIdx = !ej2_base_1.isNullOrUndefined(data.endIndex)
                ? Math.max(startIdx, data.endIndex - 1)
                : startIdx + count - 1;
            this.parent.notify(event_1.insertModel, {
                model: this.parent.getActiveSheet(),
                start: startIdx,
                end: endIdx,
                modelType: type,
                isAction: true,
                insertType: 'above'
            });
            var insertedCount = (endIdx - startIdx) + 1;
            return "Inserted " + insertedCount + " " + type + "(s) at position " + data.startIndex + ".";
        };
        AIAssist.prototype.applyDelete = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.modelType)) {
                return 'Please provide modelType (Row or Column) and startIndex.';
            }
            var type = this.normalizeModelType(data.modelType);
            if (!type) {
                return 'Invalid modelType. Please specify "Row" or "Column".';
            }
            var startIdx = Math.max(0, data.startIndex - 1);
            var count = Math.max(1, data.count);
            var endIdx = !ej2_base_1.isNullOrUndefined(data.endIndex)
                ? Math.max(startIdx, data.endIndex - 1)
                : startIdx + count - 1;
            this.parent.notify(event_1.deleteModel, {
                model: this.parent.getActiveSheet(),
                start: startIdx,
                end: endIdx,
                modelType: type,
                isAction: true
            });
            var deletedCount = (endIdx - startIdx) + 1;
            return "Deleted " + deletedCount + " " + type + "(s) starting at position " + data.startIndex + ".";
        };
        AIAssist.prototype.normalizeModelType = function (type) {
            if (ej2_base_1.isNullOrUndefined(type) || type === '') {
                return '';
            }
            var map = {
                'row': 'Row', 'rows': 'Row',
                'column': 'Column', 'columns': 'Column', 'col': 'Column', 'cols': 'Column'
            };
            return map[type.toLowerCase().trim()] || '';
        };
        AIAssist.prototype.applyAutoFill = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.dataRange) || ej2_base_1.isNullOrUndefined(data.fillRange)) {
                return 'Please provide both dataRange (source) and fillRange (target) for autofill.';
            }
            var sheetName = this.parent.getActiveSheet().name;
            var dataRange = this.getTargetRange(data.dataRange);
            var fillRange = this.getTargetRange(data.fillRange);
            var direction = this.normalizeAutoFillDirection(data.direction, dataRange, fillRange);
            var fillType = this.normalizeAutoFillType(data.fillType);
            var eventArgs = {
                dataRange: sheetName + "!" + dataRange,
                fillRange: sheetName + "!" + fillRange,
                direction: direction,
                fillType: fillType,
                cancel: false
            };
            this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'autofill' });
            Iif (eventArgs.cancel) {
                return '';
            }
            this.parent.notify(event_1.setAutoFill, {
                dataRange: eventArgs.dataRange,
                fillRange: eventArgs.fillRange,
                direction: direction,
                fillType: fillType
            });
            this.parent.notify(index_1.completeAction, {
                eventArgs: { dataRange: eventArgs.dataRange, fillRange: eventArgs.fillRange, direction: direction, fillType: fillType },
                action: 'autofill'
            });
            return "AutoFilled " + fillRange + " from " + dataRange + " (" + fillType + ", direction: " + direction + ").";
        };
        AIAssist.prototype.normalizeAutoFillDirection = function (direction, dataRange, fillRange) {
            if (!ej2_base_1.isNullOrUndefined(direction) && direction !== '') {
                var map = {
                    'down': 'Down', 'up': 'Up', 'left': 'Left', 'right': 'Right'
                };
                var normalized = map[direction.toLowerCase().trim()];
                Eif (normalized) {
                    return normalized;
                }
            }
            if (dataRange && fillRange) {
                var dataIdx = index_5.getRangeIndexes(dataRange);
                var fillIdx = index_5.getRangeIndexes(fillRange);
                if (fillIdx[0] > dataIdx[2]) {
                    return 'Down';
                }
                if (fillIdx[0] < dataIdx[0]) {
                    return 'Up';
                }
                if (fillIdx[1] > dataIdx[3]) {
                    return 'Right';
                }
                Eif (fillIdx[1] < dataIdx[1]) {
                    return 'Left';
                }
            }
            return 'Down';
        };
        AIAssist.prototype.normalizeAutoFillType = function (type) {
            if (ej2_base_1.isNullOrUndefined(type) || type === '') {
                return 'FillSeries';
            }
            var map = {
                'fillseries': 'FillSeries', 'series': 'FillSeries',
                'copycells': 'CopyCells', 'copy': 'CopyCells',
                'fillformattingonly': 'FillFormattingOnly', 'formatting': 'FillFormattingOnly',
                'fillwithoutformatting': 'FillWithoutFormatting', 'noformatting': 'FillWithoutFormatting'
            };
            return map[type.toLowerCase().replace(/\s/g, '')] || 'FillSeries';
        };
        AIAssist.prototype.applyFreezePanes = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.freezeType)) {
                return 'Please specify freezeType: "Rows", "Columns", "Panes", or "Unfreeze".';
            }
            if (!this.parent.allowFreezePane) {
                return 'Freeze pane is not enabled. Set allowFreezePane to true.';
            }
            var freezeType = data.freezeType.toLowerCase().trim();
            var row = 0;
            var column = 0;
            switch (freezeType) {
                case 'rows':
                    row = Math.max(1, data.row);
                    column = 0;
                    break;
                case 'columns':
                    row = 0;
                    column = Math.max(1, data.column);
                    break;
                case 'panes':
                    row = Math.max(1, data.row);
                    column = Math.max(1, data.column);
                    break;
                case 'unfreeze':
                    row = 0;
                    column = 0;
                    break;
                default:
                    return "Unknown freezeType \"" + data.freezeType + "\". Use \"Rows\", \"Columns\", \"Panes\", or \"Unfreeze\".";
            }
            var eventArgs = {
                row: row, column: column, cancel: false, sheetIndex: this.parent.activeSheetIndex
            };
            this.parent.notify(event_1.beginAction, { eventArgs: eventArgs, action: 'freezePanes' });
            Iif (eventArgs.cancel) {
                return '';
            }
            this.parent.freezePanes(row, column);
            this.parent.notify(index_1.completeAction, {
                eventArgs: { row: row, column: column, sheetIndex: this.parent.activeSheetIndex },
                action: 'freezePanes'
            });
            if (freezeType === 'unfreeze') {
                return 'Removed all freeze panes from the active sheet.';
            }
            return "Frozen " + (row > 0 ? row + " row(s)" : '') + (row > 0 && column > 0 ? ' and ' : '') + (column > 0 ? column + " column(s)" : '') + " on the active sheet.";
        };
        AIAssist.prototype.applyHyperlink = function (data) {
            if (ej2_base_1.isNullOrUndefined(data) || ej2_base_1.isNullOrUndefined(data.address) || data.address === '') {
                return 'Please provide an address (URL or cell/sheet reference) for the hyperlink.';
            }
            var range = this.getTargetRange(data.range);
            var sheetName = this.parent.getActiveSheet().name;
            var cellAddress = sheetName + "!" + range;
            var displayText = !ej2_base_1.isNullOrUndefined(data.displayText) && data.displayText !== ''
                ? data.displayText : null;
            this.parent.insertHyperlink(data.address, cellAddress, displayText, false);
            return "Inserted hyperlink to \"" + data.address + "\" in " + range + (displayText ? " with display text \"" + displayText + "\"" : '') + ".";
        };
        AIAssist.prototype.applySave = function (data) {
            var type = (data.saveType || 'xlsx').toLowerCase();
            var validTypes = ['xlsx', 'xls', 'csv', 'pdf'];
            if (validTypes.indexOf(type) === -1) {
                return "Saving in '" + type + "' format is not supported. Valid save types are 'xlsx', 'xls', 'csv', and 'pdf'.";
            }
            this.parent.notify(event_1.exportDialog, { item: { id: this.parent.element.id + "_" + (type[0].toUpperCase() + type.substring(1)) } });
            return 'Save dialog opened';
        };
        AIAssist.prototype.getTargetRange = function (address) {
            var sheet = this.parent.getActiveSheet();
            var fallback = sheet.selectedRange;
            if (ej2_base_1.isNullOrUndefined(address) || address === '' || address.toLowerCase() === 'selected') {
                return fallback;
            }
            return address;
        };
        AIAssist.prototype.getTargetAddress = function (address) {
            var sheet = this.parent.getActiveSheet();
            var fallback = (sheet.selectedRange).split(':')[0];
            if (ej2_base_1.isNullOrUndefined(address) || address === '' || address.toLowerCase() === 'selected') {
                return fallback;
            }
            return address.split(':')[0];
        };
        AIAssist.prototype.appendResponse = function (response, isSuccess) {
            Eif (isSuccess === void 0) { isSuccess = true; }
            Eif (response) {
                Eif (isSuccess) {
                    this.parent.trigger('promptResponse', { prompt: this.currentPrompt, response: response });
                }
                if (!ej2_base_1.isNullOrUndefined(this.aiAssistView)) {
                    this.aiAssistView.addPromptResponse(response);
                }
            }
        };
        AIAssist.prototype.destroy = function () {
            this.removeEventListener();
            if (this.aiAssistView) {
                this.aiAssistView.destroy();
                this.aiAssistView = null;
            }
            if (this.assistPanel) {
                this.assistPanel.innerHTML = '';
                this.assistPanel = null;
            }
            if (this.assistHost && this.assistHost.parentElement) {
                this.assistHost.parentElement.removeChild(this.assistHost);
                this.assistHost = null;
            }
            this.currentPrompt = '';
            this.currentPanelWidth = 328;
            this.isAIPaneVisible = false;
            this.isAIPanelResized = false;
            this.storedPrompts = null;
            this.parent = null;
        };
        AIAssist.prototype.getModuleName = function () {
            return 'AIAssist';
        };
        return AIAssist;
    }());
    exports.AIAssist = AIAssist;
    var serverAIRequest = function (context, settings) { return __awaiter(_this, void 0, void 0, function () {
        var eventArgs, response, result, error_4;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 3, , 4]);
                    eventArgs = {
                        requestData: {
                            method: 'POST', headers: { 'Content-Type': 'application/json' }, body: settings
                        }
                    };
                    context.trigger('promptRequest', eventArgs);
                    if (eventArgs.cancel) {
                        return [2, 'Request has been cancelled'];
                    }
                    eventArgs.requestData.body = JSON.stringify(eventArgs.requestData.body);
                    return [4, fetch(context.aiAssistSettings.requestUrl, eventArgs.requestData)];
                case 1:
                    response = _a.sent();
                    return [4, response.json()];
                case 2:
                    result = _a.sent();
                    Iif (!response.ok) {
                        throw new Error(result.error || 'Network response was not ok');
                    }
                    return [2, result.response.replace('END_INSERTION', '')];
                case 3:
                    error_4 = _a.sent();
                    return [2, error_4.message];
                case 4: return [2];
            }
        });
    }); };
});