All files / backend/dist/services/workspace workspace-service.js

0% Statements 0/639
0% Branches 0/346
0% Functions 0/90
0% Lines 0/604

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Workspace Service
 *
 * Manages workspace operations including:
 * - Configuration management
 * - Content operations (singles, collections, data files)
 * - Build and serve operations
 * - File operations and bundle management
 * - Image operations and thumbnails
 */
import path from 'path';
import { glob } from 'glob';
import fs from 'fs-extra';
import fssimple from 'fs';
import fm from 'front-matter';
import { promisify } from 'util';
import { isContentFile, SUPPORTED_CONTENT_EXTENSIONS } from '../../utils/content-formats.js';
import { recurForceRemove } from '../../utils/file-dir-utils.js';
import { createThumbnailJob } from '../../jobs/index.js';
import { SITE_CATEGORIES } from '../../logging/index.js';
import { frontMatterContentSchema } from '@quiqr/types';
import { isValidToString } from '../../sync/embgit-sync-base.js';
/**
 * WorkspaceService - Main service for workspace operations
 */
export class WorkspaceService {
    workspacePath;
    workspaceKey;
    siteKey;
    workspaceConfigProvider;
    formatProviderResolver;
    pathHelper;
    appConfig;
    appState;
    providerFactory;
    windowAdapter;
    shellAdapter;
    outputConsole;
    screenshotWindowManager;
    buildActionService;
    container;
    currentDevServer;
    currentSSGType;
    constructor(workspacePath, workspaceKey, siteKey, dependencies) {
        this.workspacePath = workspacePath;
        this.workspaceKey = workspaceKey;
        this.siteKey = siteKey;
        this.workspaceConfigProvider = dependencies.workspaceConfigProvider;
        this.formatProviderResolver = dependencies.formatProviderResolver;
        this.pathHelper = dependencies.pathHelper;
        this.appConfig = dependencies.appConfig;
        this.appState = dependencies.appState;
        this.providerFactory = dependencies.providerFactory;
        this.windowAdapter = dependencies.windowAdapter;
        this.shellAdapter = dependencies.shellAdapter;
        this.outputConsole = dependencies.outputConsole;
        this.screenshotWindowManager = dependencies.screenshotWindowManager;
        this.buildActionService = dependencies.buildActionService;
        this.container = dependencies.container;
    }
    /**
     * Get the workspace path
     */
    getWorkspacePath() {
        return this.workspacePath;
    }
    /**
     * Get the workspace configurations data to be used by the client
     */
    async getConfigurationsData() {
        return this.workspaceConfigProvider.readOrCreateMinimalModelConfig(this.workspacePath, this.workspaceKey);
    }
    /**
     * Clear configurations data cache
     */
    clearConfigurationsDataCache() {
        this.workspaceConfigProvider.clearCache();
    }
    /**
     * Get creator message from workspace
     */
    async getCreatorMessage() {
        const indexPath = path.join(this.workspacePath, 'quiqr', 'home', 'index.md');
        try {
            if (fs.existsSync(indexPath)) {
                const data = await fs.readFile(indexPath, 'utf8');
                const obj = await this._smartParse(indexPath, ['md'], data);
                // TODO: probably move this validation to when we parse the data
                if (typeof obj === 'object' && obj !== null && 'mainContent' in obj && isValidToString(obj.mainContent)) {
                    return obj.mainContent.toString();
                }
                else {
                    return data;
                }
            }
        }
        catch (err) {
            console.error(err);
            console.error('error checking');
        }
        return '';
    }
    /**
     * Get model parse info
     */
    async getModelParseInfo() {
        await this.workspaceConfigProvider.readOrCreateMinimalModelConfig(this.workspacePath, this.workspaceKey);
        return this.workspaceConfigProvider.getModelParseInfo();
    }
    /**
     * Smart resolve format provider for a file
     */
    async _smartResolveFormatProvider(filePath, fallbacks) {
        let formatProvider;
        if (isContentFile(filePath)) {
            if (fs.existsSync(filePath)) {
                const resolved = await this.formatProviderResolver.resolveForMdFilePromise(filePath);
                if (resolved)
                    formatProvider = resolved;
            }
        }
        else {
            const resolved = this.formatProviderResolver.resolveForFilePath(filePath);
            if (resolved)
                formatProvider = resolved;
        }
        if (formatProvider) {
            return formatProvider;
        }
        if (fallbacks) {
            for (let i = 0; i < fallbacks.length; i++) {
                if (fallbacks[i]) {
                    const resolved = this.formatProviderResolver.resolveForExtension(fallbacks[i]);
                    if (resolved) {
                        return resolved;
                    }
                }
            }
        }
        return undefined;
    }
    /**
     * Smart dump object to string using appropriate format provider
     */
    async _smartDump(filePath, formatFallbacks, obj) {
        let formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks);
        if (formatProvider === undefined || formatProvider === null) {
            formatProvider = this.formatProviderResolver.getDefaultFormat();
        }
        if (isContentFile(filePath)) {
            return formatProvider.dumpContent(obj);
        }
        else {
            return formatProvider.dump(obj);
        }
    }
    /**
     * Smart parse string to object using appropriate format provider
     */
    async _smartParse(filePath, formatFallbacks, str) {
        if (!str || str.length === 0 || !/\S/.test(str)) {
            return {};
        }
        if (isContentFile(filePath)) {
            if (formatFallbacks) {
                formatFallbacks.push('yaml');
            }
        }
        const formatProvider = await this._smartResolveFormatProvider(filePath, formatFallbacks);
        if (formatProvider === undefined) {
            console.log('formatprovider undefined');
            return {};
        }
        if (isContentFile(filePath)) {
            return formatProvider.parseFromMdFileString(str);
        }
        else {
            return formatProvider.parse(str);
        }
    }
    /**
     * Get a single content item
     */
    async getSingle(singleKey, fileOverride) {
        const config = await this.getConfigurationsData();
        const single = config.singles.find((x) => x.key === singleKey);
        if (single == null)
            throw new Error('Could not find single.');
        if (!single.file && !fileOverride) {
            throw new Error(`Single '${singleKey}' has no file configured`);
        }
        let fileLastPath = single.file || '';
        if (typeof fileOverride === 'string' && fileOverride.length > 0) {
            fileLastPath = fileOverride;
        }
        const filePath = path.join(this.workspacePath, fileLastPath);
        if (fs.existsSync(filePath)) {
            const data = await fs.readFile(filePath, 'utf8');
            let obj = await this._smartParse(filePath, [path.extname(single.file || fileLastPath).replace('.', '')], data);
            if (typeof single.pullOuterRootKey === 'string') {
                const newObj = {};
                newObj[single.pullOuterRootKey] = obj;
                obj = newObj;
            }
            return obj;
        }
        else {
            return {};
        }
    }
    /**
     * Get the folder containing a single
     */
    async getSingleFolder(singleKey) {
        const config = await this.getConfigurationsData();
        const single = config.singles.find((x) => x.key === singleKey);
        if (single == null)
            throw new Error('Could not find single.');
        if (!single.file)
            throw new Error(`Single '${singleKey}' has no file configured`);
        const filePath = path.join(this.workspacePath, single.file);
        const directory = path.dirname(filePath);
        if (fs.existsSync(directory)) {
            return directory;
        }
        else {
            return '';
        }
    }
    /**
     * Open a single in external editor
     */
    async openSingleInEditor(singleKey) {
        const config = await this.getConfigurationsData();
        const single = config.singles.find((x) => x.key === singleKey);
        if (single == null)
            throw new Error('Could not find single.');
        if (!single.file)
            throw new Error(`Single '${singleKey}' has no file configured`);
        const filePath = path.join(this.workspacePath, single.file);
        await this.shellAdapter.openPath(filePath);
    }
    /**
     * Update a single content item
     */
    async updateSingle(singleKey, document) {
        const config = await this.getConfigurationsData();
        const single = config.singles.find((x) => x.key === singleKey);
        if (single == null)
            throw new Error('Could not find single.');
        if (!single.file)
            throw new Error(`Single '${singleKey}' has no file configured`);
        const filePath = path.join(this.workspacePath, single.file);
        // Log update start
        this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Single document update started', { singleKey, filePath });
        try {
            const directory = path.dirname(filePath);
            if (!fs.existsSync(directory))
                fs.mkdirSync(directory); // ensure directory existence
            let documentClone = JSON.parse(JSON.stringify(document));
            if (typeof single.pullOuterRootKey === 'string') {
                documentClone = documentClone[single.pullOuterRootKey];
            }
            this._stripNonDocumentData(documentClone);
            const stringData = await this._smartDump(filePath, [path.extname(single.file).replace('.', '')], documentClone);
            fs.writeFileSync(filePath, stringData);
            // Log success
            this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Single document updated', { singleKey, filePath });
            return document;
        }
        catch (error) {
            // Log error
            this.container.logger.errorSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Single document update failed', {
                singleKey,
                filePath,
                error: error instanceof Error ? error.message : String(error)
            });
            throw error;
        }
    }
    /**
     * Get files from an absolute path
     */
    async getFilesFromAbsolutePath(filePath) {
        const directory = path.join(this.workspacePath, filePath);
        const globExp = '*';
        const allFiles = await glob(globExp, {
            nodir: true,
            absolute: false,
            cwd: directory,
        });
        const expression = `_?index[.](${SUPPORTED_CONTENT_EXTENSIONS.join('|')})$`;
        const pageOrSectionIndexReg = new RegExp(expression);
        const filtered = allFiles.filter((x) => !pageOrSectionIndexReg.test(x));
        const merged = filtered.map((src) => ({ src }));
        return merged;
    }
    /**
     * Get resources from content bundle
     */
    async getResourcesFromContent(filePath, currentResources = [], targetPath = null) {
        filePath = path.normalize(filePath);
        const directory = path.dirname(filePath);
        let globExp = '*';
        if (targetPath) {
            globExp = targetPath + '/*';
        }
        const allFiles = await glob(globExp, {
            nodir: true,
            absolute: false,
            cwd: directory,
        });
        const expression = `_?index[.](${SUPPORTED_CONTENT_EXTENSIONS.join('|')})$`;
        const pageOrSectionIndexReg = new RegExp(expression);
        const filtered = allFiles.filter((x) => !pageOrSectionIndexReg.test(x));
        const merged = filtered.map((src) => {
            return Object.assign({ src }, currentResources.find((r) => r.src === src));
        });
        return merged;
    }
    /**
     * Get a collection item
     */
    async getCollectionItem(collectionKey, collectionItemKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        if (await fs.exists(filePath)) {
            const stats = await fs.stat(filePath);
            if (stats.isDirectory()) {
                throw new Error(`EISDIR: illegal operation on a directory, read: ${filePath}`);
            }
            const data = await fs.readFile(filePath, { encoding: 'utf8' });
            const obj = await this._smartParse(filePath, [collection.extension], data);
            return obj;
        }
        else {
            return undefined;
        }
    }
    /**
     * Create a new collection item
     */
    async createCollectionItemKey(collectionKey, collectionItemKey, itemTitle) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        let filePath;
        let returnedKey;
        if (collection.folder.startsWith('content')) {
            returnedKey = path.join(collectionItemKey, 'index.' + collection.extension);
            filePath = path.join(this.workspacePath, collection.folder, returnedKey);
        }
        else {
            returnedKey = collectionItemKey + '.' + collection.extension;
            filePath = path.join(this.workspacePath, collection.folder, returnedKey);
        }
        if (fs.existsSync(filePath))
            return { unavailableReason: 'already-exists' };
        await fs.ensureDir(path.dirname(filePath));
        const stringData = await this._smartDump(filePath, [collection.dataformat], {
            title: itemTitle,
        });
        await fs.writeFile(filePath, stringData, { encoding: 'utf8' });
        return { key: returnedKey.replace(/\\/g, '/') };
    }
    /**
     * List collection items
     */
    async listCollectionItems(collectionKey) {
        const collection = (await this.getConfigurationsData()).collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        const folder = path.join(this.workspacePath, collection.folder).replace(/\\/g, '/');
        const supportedContentExt = ['md', 'html', 'markdown', 'qmd'];
        if (collection.folder.startsWith('content') ||
            supportedContentExt.indexOf(collection.extension) !== -1) {
            // WHEN WE WANT TO IGNORE _index.md front pages
            let subDirStars = '**';
            if ('includeSubdirs' in collection && collection.includeSubdirs === false) {
                subDirStars = '';
            }
            let globExpression = path.join(folder, `${subDirStars}/*.{${supportedContentExt.join(',')}}`).replace(/\\/g, '/');
            // WHEN WE WANT TO IGNORE _index.md front pages
            if ('hideIndex' in collection && collection.hideIndex === true) {
                globExpression = path.join(folder, `${subDirStars}/!(_index).{${supportedContentExt.join(',')}}`).replace(/\\/g, '/');
            }
            const files = await glob(globExpression, {});
            const retFiles = files.map(function (item) {
                // Use path.posix.relative: both `item` (from glob) and `folder` must be
                // normalized to forward slashes and have consistent drive letter case.
                // On Windows: glob returns backslashes and drive letter case may differ
                const normalizedFolder = folder.replace(/^[A-Z]:/, (m) => m.toLowerCase());
                const normalizedItem = item
                    .replace(/\\/g, '/') // Normalize backslashes to forward slashes
                    .replace(/^[A-Z]:/, (m) => m.toLowerCase()); // Normalize drive letter case
                const key = path.posix.relative(normalizedFolder, normalizedItem);
                const label = key.replace(/^\/?(.+)\/[^/]+$/, '$1');
                let sortval = null;
                if ('sortkey' in collection && collection.sortkey) {
                    const data = fssimple.readFileSync(item, 'utf8');
                    const rawContent = fm(data);
                    const parseResult = frontMatterContentSchema.safeParse(rawContent);
                    if (parseResult.success && collection.sortkey in parseResult.data.attributes) {
                        sortval = String(parseResult.data.attributes[collection.sortkey]);
                    }
                }
                else {
                    sortval = label;
                }
                // Detect if this is a page bundle (file is named index.md/index.html in a directory)
                const isPageBundle = /\/index\.(md|html|markdown|qmd)$/.test(item);
                return { key, label, sortval, isPageBundle };
            });
            return retFiles;
        }
        else {
            // data folder and everything else
            const globExpression = path.join(folder, `**/*.{${this.formatProviderResolver.allFormatsExt().join(',')}}`).replace(/\\/g, '/');
            const files = await glob(globExpression, {});
            return files.map(function (item) {
                // On Windows: glob returns backslashes and drive letter case may differ
                const normalizedFolder = folder.replace(/^[A-Z]:/, (m) => m.toLowerCase());
                const normalizedItem = item
                    .replace(/\\/g, '/') // Normalize backslashes to forward slashes
                    .replace(/^[A-Z]:/, (m) => m.toLowerCase()); // Normalize drive letter case
                const key = path.posix.relative(normalizedFolder, normalizedItem);
                const label = key;
                const sortval = key; // Default sortval to key for data folders
                return { key, label, sortval };
            });
        }
    }
    /**
     * Strip non-document data (internal fields starting with __)
     */
    _stripNonDocumentData(document) {
        for (const key in document) {
            if (key.startsWith('__')) {
                delete document[key];
            }
        }
    }
    /**
     * Rename a collection item
     */
    async renameCollectionItem(collectionKey, collectionItemKey, collectionItemNewKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        let filePath;
        let newFilePath;
        let newFileKey;
        let newLabel;
        if (collectionItemKey.includes('.' + collection.extension)) {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
            newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey + '.' + collection.extension);
            newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
            newLabel = collectionItemNewKey + '.' + collection.extension;
        }
        else {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
            newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey);
            newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
            newLabel = collectionItemNewKey;
        }
        if (!fs.existsSync(filePath)) {
            console.log('orig does not exist' + filePath);
        }
        if (fs.existsSync(newFilePath)) {
            console.log('new already  exist' + newFilePath);
            return { renamed: false };
        }
        fs.renameSync(filePath, newFilePath);
        return { renamed: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
    }
    /**
     * Copy collection item to another language
     */
    async copyCollectionItemToLang(collectionKey, collectionItemKey, collectionItemNewKey, destLangCode) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        let newFilePath;
        let newFileKey;
        let newLabel;
        const langs = await this.getHugoConfigLanguages();
        const sourcelang = langs.find((lang) => {
            return collection.folder.startsWith(lang.source);
        });
        const destlang = langs.find((lang) => {
            return lang.lang == destLangCode;
        });
        if (!sourcelang || !destlang) {
            return { copied: false };
        }
        const pathInLang = collection.folder.slice(sourcelang.source.length);
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        if (collectionItemKey.includes('.' + collection.extension)) {
            newFilePath = path.join(this.workspacePath, destlang.source, pathInLang, collectionItemNewKey + '.' + collection.extension);
            newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
            newLabel = collectionItemNewKey + '.' + collection.extension;
        }
        else {
            newFilePath = path.join(this.workspacePath, destlang.source, pathInLang, collectionItemNewKey);
            newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
            newLabel = collectionItemNewKey;
        }
        if (!fs.existsSync(filePath)) {
            console.log('orig does not exist' + filePath);
            return { copied: false };
        }
        if (fs.existsSync(newFilePath)) {
            console.log('new already  exist' + newFilePath);
            return { copied: false };
        }
        fs.copySync(filePath, newFilePath);
        return { copied: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
    }
    /**
     * Copy a collection item
     */
    async copyCollectionItem(collectionKey, collectionItemKey, collectionItemNewKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        let filePath;
        let newFilePath;
        let newFileKey;
        let newLabel;
        if (collectionItemKey.includes('.' + collection.extension)) {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
            newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey + '.' + collection.extension);
            newFileKey = path.join(collectionItemNewKey + '.' + collection.extension);
            newLabel = collectionItemNewKey + '.' + collection.extension;
        }
        else {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
            newFilePath = path.join(this.workspacePath, collection.folder, collectionItemNewKey);
            newFileKey = path.join(collectionItemNewKey, 'index.' + collection.extension);
            newLabel = collectionItemNewKey;
        }
        if (!fs.existsSync(filePath)) {
            console.log('orig does not exist' + filePath);
            return { copied: false };
        }
        if (fs.existsSync(newFilePath)) {
            console.log('new already  exist' + newFilePath);
            return { copied: false };
        }
        fs.copySync(filePath, newFilePath);
        return { copied: true, item: { key: newFileKey.replace(/\\/g, '/'), label: newLabel } };
    }
    /**
     * Delete a collection item
     */
    async deleteCollectionItem(collectionKey, collectionItemKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        let filePath = '';
        if (collectionItemKey.endsWith('/index.md')) {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey.split('/')[0]);
        }
        else {
            filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        }
        await recurForceRemove(filePath);
        return true;
    }
    /**
     * Make a collection item into a page bundle
     */
    async makePageBundleCollectionItem(collectionKey, collectionItemKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        if (fs.existsSync(filePath)) {
            const newdir = path.join(this.workspacePath, collection.folder, collectionItemKey.split('.').slice(0, -1).join('.'));
            fs.mkdirSync(newdir);
            fs.renameSync(filePath, path.join(newdir, 'index.md'));
            return true;
        }
        return false;
    }
    /**
     * Open collection item in external editor
     */
    async openCollectionItemInEditor(collectionKey, collectionItemKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        await this.shellAdapter.openPath(filePath);
    }
    /**
     * Get collection by key
     */
    async getCollectionByKey(collectionKey) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        return collection;
    }
    /**
     * Build a collection item using a build action
     */
    async buildCollectionItem(collectionKey, collectionItemKey, buildAction) {
        const collection = await this.getCollectionByKey(collectionKey);
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        const buildActionDict = collection.build_actions?.find((x) => x.key === buildAction);
        if (!buildActionDict) {
            throw new Error(`Build action ${buildAction} not found in collection ${collectionKey}`);
        }
        return this.buildActionService.runAction(buildAction, buildActionDict.execute, filePath, this.workspacePath, this.siteKey, this.workspaceKey);
    }
    /**
     * Build a single using a build action
     */
    async buildSingle(singleKey, buildAction) {
        const config = await this.getConfigurationsData();
        const single = config.singles.find((x) => x.key === singleKey);
        if (single == null)
            throw new Error('Could not find single.');
        if (!single.file)
            throw new Error(`Single '${singleKey}' has no file configured`);
        const filePath = path.join(this.workspacePath, single.file);
        const buildActionDict = single.build_actions?.find((x) => x.key === buildAction);
        if (!buildActionDict) {
            throw new Error(`Build action ${buildAction} not found in single ${singleKey}`);
        }
        return this.buildActionService.runAction(buildAction, buildActionDict.execute, filePath, this.workspacePath, this.siteKey, this.workspaceKey);
    }
    /**
     * Update a collection item
     */
    async updateCollectionItem(collectionKey, collectionItemKey, document) {
        const config = await this.getConfigurationsData();
        const collection = config.collections.find((x) => x.key === collectionKey);
        if (collection == null)
            throw new Error('Could not find collection.');
        const filePath = path.join(this.workspacePath, collection.folder, collectionItemKey);
        // Log update start
        this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Collection item update started', { collectionKey, collectionItemKey, filePath });
        try {
            const directory = path.dirname(filePath);
            if (!fs.existsSync(directory))
                fs.mkdirSync(directory); // ensure directory existence
            const documentClone = JSON.parse(JSON.stringify(document));
            this._stripNonDocumentData(documentClone);
            const stringData = await this._smartDump(filePath, [collection.dataformat], documentClone);
            fs.writeFileSync(filePath, stringData);
            // Log success
            this.container.logger.infoSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Collection item updated', { collectionKey, collectionItemKey, filePath });
            return document;
        }
        catch (error) {
            // Log error
            this.container.logger.errorSite(this.siteKey, this.workspaceKey, SITE_CATEGORIES.CONTENT, 'Collection item update failed', {
                collectionKey,
                collectionItemKey,
                filePath,
                error: error instanceof Error ? error.message : String(error)
            });
            throw error;
        }
    }
    /**
     * Copy files into a collection item or single
     */
    async copyFilesIntoCollectionItem(collectionKey, collectionItemKey, targetPath, files, forceFileName) {
        const config = await this.getConfigurationsData();
        let filesBasePath = '';
        // When file starts with / use the root of the site directory
        if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
            filesBasePath = path.join(this.workspacePath, targetPath);
        }
        else {
            if (collectionKey == '') {
                filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
            }
            else {
                const collection = config.collections.find((x) => x.key === collectionKey);
                if (collection == null)
                    throw new Error('Could not find collection.');
                // Check if item is already a bundle (has directory separator)
                if (!collectionItemKey.includes('/')) {
                    const itemPath = path.join(this.workspacePath, collection.folder, collectionItemKey);
                    const bundleDirPath = path.join(this.workspacePath, collection.folder, collectionItemKey.replace(/\.[^.]+$/, ''));
                    // Check if we need to convert to bundle
                    if (fs.existsSync(itemPath) && fs.statSync(itemPath).isFile()) {
                        // File exists as non-bundle - convert it
                        await this.makePageBundleCollectionItem(collectionKey, collectionItemKey);
                    }
                    // If bundle directory already exists (either just converted or already was converted), update the key
                    if (fs.existsSync(bundleDirPath) && fs.statSync(bundleDirPath).isDirectory()) {
                        collectionItemKey = collectionItemKey.replace(/\.[^.]+$/, '') + '/index.md';
                    }
                }
                // Extract the bundle directory from collectionItemKey
                // For bundle items like "project1/index.md", extract "project1"
                let bundleDir = collectionItemKey;
                if (collectionItemKey.includes('/')) {
                    // Has directory separator - strip the filename part
                    bundleDir = collectionItemKey.replace(/\/[^/]+$/, '');
                }
                else {
                    // No directory separator - strip the file extension (shouldn't happen after auto-convert)
                    bundleDir = collectionItemKey.replace(/\.[^.]+$/, '');
                }
                const pathFromItemRoot = path.join(bundleDir, targetPath);
                filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
            }
        }
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const from = file;
            let to = path.join(filesBasePath, path.basename(file));
            if (i == 0 && forceFileName) {
                to = path.join(filesBasePath, forceFileName);
                files[0] = forceFileName;
            }
            const toExists = fs.existsSync(to);
            if (toExists) {
                fs.unlinkSync(to);
            }
            await fs.copy(from, to);
        }
        return files.map((x) => {
            return path.join(targetPath, path.basename(x)).replace(/\\/g, '/');
        });
    }
    /**
     * Delete a file from a bundle path.
     * Used when removing files from bundle manager.
     */
    async deleteFileFromBundle(collectionKey, collectionItemKey, targetPath, filename) {
        const config = await this.getConfigurationsData();
        let filesBasePath = '';
        // When path starts with / use the root of the site directory
        if (targetPath.charAt(0) === '/' || targetPath.charAt(0) === '\\') {
            filesBasePath = path.join(this.workspacePath, targetPath);
        }
        else {
            if (collectionKey === '') {
                filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
            }
            else {
                const collection = config.collections.find((x) => x.key === collectionKey);
                if (collection == null)
                    throw new Error('Could not find collection.');
                const pathFromItemRoot = path.join(collectionItemKey.replace(/\/[^/]+$/, ''), targetPath);
                filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
            }
        }
        const filePath = path.join(filesBasePath, filename);
        if (fs.existsSync(filePath)) {
            await recurForceRemove(filePath);
            return true;
        }
        return false;
    }
    /**
     * Upload a file to a bundle path with base64 content.
     * Used by native browser file pickers.
     * Returns the uploaded file path and optionally the new collection item key if converted to bundle.
     */
    async uploadFileToBundlePath(collectionKey, collectionItemKey, targetPath, filename, base64Content) {
        const config = await this.getConfigurationsData();
        const originalCollectionItemKey = collectionItemKey;
        let wasConverted = false;
        let filesBasePath = '';
        // When path starts with / use the root of the site directory
        if (targetPath.charAt(0) === '/' || targetPath.charAt(0) === '\\') {
            filesBasePath = path.join(this.workspacePath, targetPath);
        }
        else {
            if (collectionKey === '') {
                filesBasePath = path.join(await this.getSingleFolder(collectionItemKey), targetPath);
            }
            else {
                const collection = config.collections.find((x) => x.key === collectionKey);
                if (collection == null)
                    throw new Error('Could not find collection.');
                // Check if item is already a bundle (has directory separator)
                if (!collectionItemKey.includes('/')) {
                    const itemPath = path.join(this.workspacePath, collection.folder, collectionItemKey);
                    const bundleDirPath = path.join(this.workspacePath, collection.folder, collectionItemKey.replace(/\.[^.]+$/, ''));
                    // Check if we need to convert to bundle
                    if (fs.existsSync(itemPath) && fs.statSync(itemPath).isFile()) {
                        // File exists as non-bundle - convert it
                        await this.makePageBundleCollectionItem(collectionKey, collectionItemKey);
                        wasConverted = true;
                    }
                    // If bundle directory already exists (either just converted or already was converted), update the key
                    if (fs.existsSync(bundleDirPath) && fs.statSync(bundleDirPath).isDirectory()) {
                        collectionItemKey = collectionItemKey.replace(/\.[^.]+$/, '') + '/index.md';
                    }
                }
                // Extract the bundle directory from collectionItemKey
                // For bundle items like "project1/index.md", extract "project1"
                let bundleDir = collectionItemKey;
                if (collectionItemKey.includes('/')) {
                    // Has directory separator - strip the filename part
                    bundleDir = collectionItemKey.replace(/\/[^/]+$/, '');
                }
                else {
                    // No directory separator - strip the file extension (shouldn't happen after auto-convert)
                    bundleDir = collectionItemKey.replace(/\.[^.]+$/, '');
                }
                const pathFromItemRoot = path.join(bundleDir, targetPath);
                filesBasePath = path.join(this.workspacePath, collection.folder, pathFromItemRoot);
            }
        }
        // Ensure the target directory exists
        await fs.ensureDir(filesBasePath);
        const filePath = path.join(filesBasePath, filename);
        // If file exists, remove it first
        if (fs.existsSync(filePath)) {
            fs.unlinkSync(filePath);
        }
        // Decode base64 and write file
        const buffer = Buffer.from(base64Content, 'base64');
        await fs.writeFile(filePath, buffer);
        // Return the relative path from targetPath and new key if converted
        const result = {
            uploadedPath: path.join(targetPath, filename).replace(/\\/g, '/')
        };
        if (wasConverted && collectionItemKey !== originalCollectionItemKey) {
            result.newCollectionItemKey = collectionItemKey;
        }
        return result;
    }
    /**
     * Check if path exists (promisified)
     */
    existsPromise(src) {
        return new Promise((resolve) => {
            fs.exists(src, (exists) => {
                resolve(exists);
            });
        });
    }
    /**
     * Remove thumbnail for item image
     */
    async removeThumbnailForItemImage(collectionKey, collectionItemKey, targetPath) {
        let folder;
        const itemPath = collectionItemKey.replace(/\/[^/]+$/, '');
        if (collectionKey == '') {
            folder = path.basename(await this.getSingleFolder(collectionItemKey));
        }
        else {
            const config = await this.getConfigurationsData();
            const collection = config.collections.find((x) => x.key === collectionKey);
            if (!collection) {
                throw new Error('Could not find collection.');
            }
            folder = collection.folder;
        }
        let thumbSrc = path.join(this.workspacePath, '.quiqr-cache/thumbs', folder, itemPath, targetPath);
        if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
            thumbSrc = path.join(this.workspacePath, '.quiqr-cache/thumbs', targetPath);
        }
        const thumbSrcExists = await this.existsPromise(thumbSrc);
        if (thumbSrcExists) {
            fs.remove(thumbSrc);
        }
    }
    /**
     * Get files in a bundle
     */
    async getFilesInBundle(collectionKey, collectionItemKey, targetPath, extensions, forceFileName) {
        const show = false;
        if (show) {
            console.log(forceFileName);
            console.log(extensions);
        }
        let files = [];
        let folder;
        let filePath;
        const config = await this.getConfigurationsData();
        if (collectionKey == '') {
            const single = config.singles.find((x) => x.key === collectionItemKey);
            if (single == null)
                throw new Error('Could not find single.');
            if (!single.file)
                throw new Error(`Single '${collectionItemKey}' has no file configured`);
            filePath = path.join(this.workspacePath, single.file);
        }
        else {
            const collection = config.collections.find((x) => x.key === collectionKey);
            if (!collection) {
                throw new Error('Could not find collection.');
            }
            folder = collection.folder;
            filePath = path.join(this.workspacePath, folder, collectionItemKey);
        }
        if (await fs.exists(filePath)) {
            if (isContentFile(filePath)) {
                files = await this.getResourcesFromContent(filePath, [], targetPath);
            }
            return files;
        }
    }
    /**
     * Get thumbnail for collection or single item image
     */
    async getThumbnailForCollectionOrSingleItemImage(collectionKey, itemKey, targetPath) {
        const itemPath = itemKey.replace(/\/[^/]+$/, '');
        if (targetPath.charAt(0) == '/' || targetPath.charAt(0) == '\\') {
            return this.getThumbnailForAbsoluteImgPath(path.join(this.workspacePath, targetPath), targetPath);
        }
        else if (collectionKey == '') {
            return this.getThumbnailForAbsoluteImgPath(path.join(await this.getSingleFolder(itemKey), targetPath), // complete path
            targetPath, // targetPath
            path.basename(await this.getSingleFolder(itemKey)), // folder
            itemPath);
        }
        else {
            const config = await this.getConfigurationsData();
            const collection = config.collections.find((x) => x.key === collectionKey);
            if (collection == null)
                throw new Error('Could not find collection.');
            const folder = collection.folder;
            return this.getThumbnailForAbsoluteImgPath(path.join(this.workspacePath, collection.folder, itemPath, targetPath), // completePath
            targetPath, folder, itemPath);
        }
    }
    /**
     * Get thumbnail for absolute image path
     */
    async getThumbnailForAbsoluteImgPath(completePath, targetPath, folder = '', itemPath = '') {
        const srcExists = await this.existsPromise(completePath);
        if (!srcExists) {
            return 'NOT_FOUND';
        }
        const thumbSrc = path.join(this.workspacePath, '.quiqr-cache/thumbs', folder, itemPath, targetPath);
        const thumbSrcExists = await this.existsPromise(thumbSrc);
        let ext = path.extname(thumbSrc).replace('.', '').toLowerCase();
        if (ext === 'png' ||
            ext === 'jpg' ||
            ext === 'jpeg' ||
            ext === 'svg' ||
            ext === 'gif') {
            if (!thumbSrcExists) {
                try {
                    await createThumbnailJob(completePath, thumbSrc);
                }
                catch {
                    return 'NOT_FOUND';
                }
            }
            if (ext === 'svg')
                ext = 'svg+xml';
            const mime = `image/${ext}`;
            const buffer = await promisify(fs.readFile)(thumbSrc);
            const base64 = buffer.toString('base64');
            return `data:${mime};base64,${base64}`;
        }
        else {
            return 'NO_IMAGE';
        }
    }
    /**
     * Find first match or default in array
     */
    _findFirstMatchOrDefault(arr, key) {
        let result;
        if (key) {
            result = (arr || []).find((x) => x.key === key);
            if (result)
                return result;
        }
        result = (arr || []).find((x) => x.key === 'default' || x.key === '' || x.key == null);
        if (result)
            return result;
        if (arr !== undefined && arr.length === 1)
            return arr[0];
        if (key) {
            throw new Error(`Could not find a config for key "${key}" and a default value was not available.`);
        }
        else {
            throw new Error(`Could not find a default config.`);
        }
    }
    /**
     * Set current base URL from SSG config
     */
    async setCurrentBaseUrl(ssgType, ssgVersion, configFile) {
        // Reset currentBaseUrl
        this.appState.currentBaseUrl = undefined;
        try {
            const provider = await this.providerFactory.getProvider(ssgType);
            const configQuerier = provider.createConfigQuerier(this.workspacePath, ssgVersion, configFile);
            if (!configQuerier) {
                return; // Provider doesn't support config querying
            }
            const lines = await configQuerier.getConfigLines();
            const key = 'baseurl';
            const item = lines.find((element) => {
                return element.startsWith(key);
            });
            if (item) {
                // TOML
                let currentBaseUrl;
                if (item.includes('=')) {
                    currentBaseUrl = item.split('=')[1].replace(/"/g, '').trim();
                }
                // YAML
                else {
                    currentBaseUrl = item.replace('baseurl:', '').replace(/"/g, '').trim();
                }
                // TODO JSON
                if (currentBaseUrl && currentBaseUrl !== '/') {
                    try {
                        const url = new URL(currentBaseUrl);
                        this.appState.currentBaseUrl = url.pathname;
                    }
                    catch {
                        // Invalid URL, leave currentBaseUrl as undefined
                    }
                }
            }
        }
        catch (error) {
            // If config querying fails, just leave currentBaseUrl as undefined
            console.warn('Failed to query SSG config for baseURL:', error);
        }
    }
    /**
     * Get SSG config languages (Hugo-specific feature)
     */
    async getHugoConfigLanguages() {
        const workspaceDetails = await this.getConfigurationsData();
        try {
            let serveConfig = null;
            if (workspaceDetails.serve && workspaceDetails.serve.length) {
                serveConfig = this._findFirstMatchOrDefault(workspaceDetails.serve, '');
            }
            else {
                serveConfig = { config: '' };
            }
            const provider = await this.providerFactory.getProvider(workspaceDetails.ssgType);
            const configQuerier = provider.createConfigQuerier(this.workspacePath, workspaceDetails.ssgVersion, serveConfig.config);
            if (!configQuerier) {
                return []; // Provider doesn't support config querying
            }
            const config = await configQuerier.getConfig();
            if (!config.mounts) {
                return [];
            }
            // config.mounts can be either an array or an object with a mounts property
            // TODO: fix this weirdness with the mounts??
            const mountsArray = Array.isArray(config.mounts)
                ? config.mounts
                : config.mounts.mounts;
            if (!Array.isArray(mountsArray)) {
                return [];
            }
            const filteredArray = mountsArray.filter((mount) => {
                return 'lang' in mount;
            });
            return filteredArray;
        }
        catch (error) {
            console.warn('Failed to query SSG config languages:', error);
            return [];
        }
    }
    /**
     * Start SSG development server
     * Note: SSG binary must be pre-downloaded by the frontend before calling this method.
     * The frontend coordinates downloads via SSE to show progress to the user.
     */
    async serve() {
        const workspaceDetails = await this.getConfigurationsData();
        const { ssgType, ssgVersion } = workspaceDetails;
        // Verify SSG binary is installed (if required) - frontend is responsible for downloading it first
        const provider = await this.providerFactory.getProvider(ssgType);
        const metadata = provider.getMetadata();
        if (metadata.requiresBinary) {
            const ssgBin = this.pathHelper.getSSGBinForVer(ssgType, ssgVersion);
            if (!fs.existsSync(ssgBin)) {
                throw new Error(`${metadata.name} version ${ssgVersion} is not installed. ` +
                    `Please wait for the download to complete before starting the server.`);
            }
        }
        // Get serve configuration
        let serveConfig;
        if (workspaceDetails.serve && workspaceDetails.serve.length) {
            serveConfig = this._findFirstMatchOrDefault(workspaceDetails.serve, '');
        }
        else {
            serveConfig = { config: '' };
        }
        // Set current base URL
        await this.setCurrentBaseUrl(ssgType, ssgVersion, serveConfig.config);
        // Create dev server config
        const serverConfig = {
            workspacePath: this.workspacePath,
            version: ssgVersion,
            configFile: serveConfig.config,
            siteKey: this.siteKey,
            workspaceKey: this.workspaceKey,
        };
        // Create and start dev server
        this.currentDevServer = provider.createDevServer(serverConfig);
        this.currentSSGType = ssgType;
        try {
            await this.currentDevServer.serve();
            // Make screenshot if no screenshots are made already
            const screenshotDir = path.join(this.workspacePath, 'quiqr', 'etalage', 'screenshots');
            if (!fs.existsSync(screenshotDir)) {
                console.log('autocreate screenshots');
                this.genereateEtalageImages();
            }
        }
        catch (error) {
            // Clean up on error
            this.currentDevServer = undefined;
            this.currentSSGType = undefined;
            throw error;
        }
    }
    /**
     * Stop the dev server if running
     */
    stopHugoServer() {
        if (this.currentDevServer) {
            this.currentDevServer.stopIfRunning();
            this.currentDevServer = undefined;
            this.currentSSGType = undefined;
        }
    }
    /**
     * Build the SSG site
     */
    async build(buildKey, extraConfig = {}) {
        const workspaceDetails = await this.getConfigurationsData();
        const { ssgType, ssgVersion } = workspaceDetails;
        // Get build configuration
        let buildConfig;
        if (workspaceDetails.build && workspaceDetails.build.length) {
            buildConfig = this._findFirstMatchOrDefault(workspaceDetails.build, buildKey || '');
        }
        else {
            buildConfig = { config: '' };
        }
        const destination = path.join(this.pathHelper.getBuildDir(this.workspacePath), 'public');
        // Create build config
        const builderConfig = {
            workspacePath: this.workspacePath,
            version: ssgVersion,
            configFile: buildConfig.config,
            destination: destination,
        };
        if (extraConfig.overrideBaseURLSwitch) {
            builderConfig.baseUrl = extraConfig.overrideBaseURL;
        }
        // Create and execute builder
        const provider = await this.providerFactory.getProvider(ssgType);
        const builder = provider.createBuilder(builderConfig);
        await builder.build();
    }
    /**
     * Generate etalage (showcase) images
     */
    async genereateEtalageImages() {
        await recurForceRemove(this.pathHelper.workspaceCacheThumbsPath(this.workspacePath, path.join('quiqr', 'etalage', 'screenshots')));
        await recurForceRemove(this.pathHelper.workspaceCacheThumbsPath(this.workspacePath, path.join('quiqr', 'etalage', 'favicon')));
        const etalageDir = path.join(this.workspacePath, 'quiqr', 'etalage');
        this.screenshotWindowManager.createScreenshotAndFavicon('localhost', 13131, etalageDir);
    }
    /**
     * Get the current dev server instance
     */
    getCurrentHugoServer() {
        return this.currentDevServer;
    }
}