All files / backend/dist/services/workspace workspace-config-provider.js

0% Statements 0/177
0% Branches 0/94
0% Functions 0/26
0% Lines 0/173

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Workspace Config Provider
 *
 * Loads, parses, validates, and caches workspace configuration files.
 * Handles includes, partials, and remote config merging.
 */
import fs from 'fs-extra';
import path from 'path';
import { glob } from 'glob';
import deepmerge from 'deepmerge';
/**
 * Convert Windows backslash paths to forward slashes for glob compatibility
 */
function toGlobPath(p) {
    return p.replace(/\\/g, '/');
}
import { isRecord } from '../../utils/format-providers/types.js';
import { WorkspaceConfigValidator } from './workspace-config-validator.js';
import { InitialWorkspaceConfigBuilder } from './initial-workspace-config-builder.js';
import { FileCacheToken } from './file-cache-token.js';
/**
 * WorkspaceConfigProvider loads and manages workspace configuration
 * Uses dependency injection instead of global state
 */
export class WorkspaceConfigProvider {
    cache = {};
    parseInfo = {
        baseFile: '',
        includeFiles: [],
        includeFilesSub: [],
        partialFiles: [],
    };
    formatProviderResolver;
    pathHelper;
    unifiedConfig;
    environmentInfo;
    constructor(formatProviderResolver, pathHelper, unifiedConfig, environmentInfo) {
        this.formatProviderResolver = formatProviderResolver;
        this.pathHelper = pathHelper;
        this.unifiedConfig = unifiedConfig;
        this.environmentInfo = environmentInfo;
    }
    /**
     * Clear the configuration cache
     */
    clearCache() {
        this.cache = {};
        this.parseInfo = {
            baseFile: '',
            includeFiles: [],
            includeFilesSub: [],
            partialFiles: [],
        };
    }
    /**
     * Read or create minimal model config for a workspace
     */
    async readOrCreateMinimalModelConfig(workspacePath, workspaceKey) {
        let filePath = this.getQuiqrModelBasePath(workspacePath);
        this.parseInfo.baseFile = filePath || '';
        let token;
        if (filePath != null) {
            const cached = this.cache[filePath];
            token = await new FileCacheToken([filePath]).build();
            if (cached != null) {
                if (await cached.token.match(token)) {
                    // can be reused
                    return cached.config;
                }
            }
        }
        else {
            // File is missing > need to build default config and update cache
            // CREATE quiqr/model/base.yaml and some other default files
            const configBuilder = new InitialWorkspaceConfigBuilder(workspacePath, this.formatProviderResolver, this.pathHelper);
            filePath = configBuilder.buildAll();
            token = await new FileCacheToken([filePath]).build();
        }
        const config = await this._loadConfigurationsData(filePath, workspaceKey, workspacePath);
        config.path = workspacePath;
        config.key = workspaceKey;
        this.cache[filePath] = { token, config };
        return config;
    }
    /**
     * Get path of quiqr/model/base.{yaml|toml|json}
     */
    getQuiqrModelBasePath(workspacePath) {
        const fileExpPrimary = path.join(workspacePath, 'quiqr', 'model', 'base.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        const primaryFiles = glob.sync(toGlobPath(fileExpPrimary));
        if (primaryFiles.length > 0) {
            return primaryFiles[0];
        }
        const fileExpFallback = path.join(workspacePath, 'sukoh.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        const fallbackFiles = glob.sync(toGlobPath(fileExpFallback));
        return fallbackFiles[0];
    }
    /**
     * Load configuration data from file
     */
    async _loadConfigurationsData(filePath, workspaceKey, workspacePath) {
        const strData = fs.readFileSync(filePath, 'utf8');
        let formatProvider = this.formatProviderResolver.resolveForFilePath(filePath);
        if (formatProvider == null) {
            formatProvider = this.formatProviderResolver.getDefaultFormat();
        }
        const dataPhase1Parse = formatProvider.parse(strData);
        if (!isRecord(dataPhase1Parse)) {
            throw new Error(`Invalid config file format: ${filePath} - expected object`);
        }
        const dataPhase2Merged = await this._postProcessConfigObject(dataPhase1Parse, workspacePath);
        // Validate and migrate the config using Zod schemas
        // The validator mutates the config to apply migrations (hugover -> ssgType/ssgVersion)
        const validator = new WorkspaceConfigValidator();
        const validationError = validator.validate(dataPhase2Merged);
        if (validationError) {
            throw new Error(validationError);
        }
        // After successful validation, the config conforms to WorkspaceConfig
        // The cast is safe here because the validator has verified the structure
        return dataPhase2Merged;
    }
    /**
     * Ensure config object has required structure
     * Builds a PartialWorkspaceConfig with defaults for missing arrays
     */
    configObjectSkeleton(configOrg) {
        return {
            ...configOrg,
            menu: Array.isArray(configOrg.menu) ? configOrg.menu : [],
            collections: Array.isArray(configOrg.collections)
                ? configOrg.collections
                : [],
            singles: Array.isArray(configOrg.singles)
                ? configOrg.singles
                : [],
            dynamics: Array.isArray(configOrg.dynamics)
                ? configOrg.dynamics
                : [],
        };
    }
    /**
     * Post-process config object: load includes and merge partials
     */
    async _postProcessConfigObject(configOrg, workspacePath) {
        let config = this.configObjectSkeleton(configOrg);
        // LOAD AND MERGE INCLUDES
        const siteModelIncludes = path.join(workspacePath, 'quiqr', 'model', 'includes', '*.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        config = this._loadIncludes(config, siteModelIncludes, true);
        const siteModelIncludesSingles = path.join(workspacePath, 'quiqr', 'model', 'includes', 'singles', '*.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        config = this._loadIncludesSub('singles', config, siteModelIncludesSingles, true);
        const siteModelIncludesCollections = path.join(workspacePath, 'quiqr', 'model', 'includes', 'collections', '*.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        config = this._loadIncludesSub('collections', config, siteModelIncludesCollections, true);
        const siteModelIncludesMenus = path.join(workspacePath, 'quiqr', 'model', 'includes', 'menus', '*.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        config = this._loadIncludesSub('menu', config, siteModelIncludesMenus, true);
        const dogFoodIncludes = path.join(this.pathHelper.getApplicationResourcesDir(this.environmentInfo), 'all', 'dog_food_model/includes', '*.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
        config = this._loadIncludes(config, dogFoodIncludes, false);
        // MERGE PARTIALS
        const mergedDataCollections = await Promise.all(config.collections.map((x) => this.getMergePartialResult(x, workspacePath)));
        config.collections = mergedDataCollections;
        const mergedDataSingles = await Promise.all(config.singles.map((x) => this.getMergePartialResult(x, workspacePath)));
        config.singles = mergedDataSingles;
        const mergedDataDynamics = await Promise.all(config.dynamics.map((x) => this.getMergePartialResult(x, workspacePath)));
        config.dynamics = mergedDataDynamics;
        // CLEANUP
        if (config.menu.length < 1)
            delete config.menu;
        if (config.collections.length < 1)
            delete config.collections;
        if (config.singles.length < 1)
            delete config.singles;
        if (config.dynamics.length < 1)
            delete config.dynamics;
        return config;
    }
    /**
     * Get merge partial result
     */
    async getMergePartialResult(mergeKey, workspacePath) {
        const result = await this._mergePartials(mergeKey, workspacePath);
        return result;
    }
    /**
     * Get remote partials cache directory
     */
    partialRemoteCacheDir(workspacePath) {
        return path.join(workspacePath, 'quiqr', 'model', 'partialsRemoteCache');
    }
    /**
     * Create remote partials cache directory
     */
    createPartialsRemoteCacheDir(workspacePath) {
        const filePartialDir = this.partialRemoteCacheDir(workspacePath);
        fs.ensureDirSync(filePartialDir);
        return filePartialDir;
    }
    /**
     * Load includes and merge into config object
     * Handles both object includes (merged by key) and array includes (for collections, singles, menu, dynamics)
     */
    _loadIncludes(configObject, fileIncludes, showInParseInfo) {
        const files = glob.sync(toGlobPath(fileIncludes));
        const newObject = {};
        // Track array includes separately to merge with existing arrays
        const arrayKeys = ['collections', 'singles', 'dynamics', 'menu'];
        files.forEach((filename) => {
            const strData = fs.readFileSync(filename, 'utf8');
            let formatProvider = this.formatProviderResolver.resolveForFilePath(filename);
            if (formatProvider == null) {
                formatProvider = this.formatProviderResolver.getDefaultFormat();
            }
            const mergeData = formatProvider.parse(strData);
            const key = path.parse(filename).name;
            if (showInParseInfo) {
                this.parseInfo.includeFiles.push({ key, filename });
            }
            // Handle array includes (collections.yaml, singles.yaml, menu.yaml, dynamics.yaml)
            if (Array.isArray(mergeData) && arrayKeys.includes(key)) {
                const existingArray = configObject[key];
                if (Array.isArray(existingArray)) {
                    // Concatenate with existing array
                    newObject[key] = [...existingArray, ...mergeData];
                }
                else {
                    newObject[key] = mergeData;
                }
                return;
            }
            // Handle object includes (merged by key)
            if (!isRecord(mergeData)) {
                return;
            }
            const existingValue = configObject[key];
            newObject[key] = deepmerge(mergeData, isRecord(existingValue) ? existingValue : {});
        });
        return { ...configObject, ...newObject };
    }
    /**
     * Load sub-includes (singles, collections, menus)
     */
    _loadIncludesSub(modelType, configObject, fileIncludes, showInParseInfo) {
        const files = glob.sync(toGlobPath(fileIncludes));
        const newObject = { ...configObject };
        files.forEach((filename) => {
            const strData = fs.readFileSync(filename, 'utf8');
            let formatProvider = this.formatProviderResolver.resolveForFilePath(filename);
            if (formatProvider == null) {
                formatProvider = this.formatProviderResolver.getDefaultFormat();
            }
            const mergeDataSub = formatProvider.parse(strData);
            if (showInParseInfo) {
                this.parseInfo.includeFilesSub.push({ key: modelType, filename: filename });
            }
            if (modelType === 'menu') {
                // Menu items are MenuSection objects
                newObject.menu.push(mergeDataSub);
            }
            else {
                // Singles and collections are MergeableConfigItem objects
                newObject[modelType].push(mergeDataSub);
            }
        });
        return newObject;
    }
    /**
     * Get encoded destination path for remote partials
     */
    getEncodedDestinationPath(filePartialDir, mergeKey) {
        const encodeFilename = encodeURIComponent(mergeKey._mergePartial);
        return path.join(filePartialDir, encodeFilename);
    }
    /**
     * Type guard to check if a config item has _mergePartial property
     */
    hasMergePartial(item) {
        return '_mergePartial' in item && typeof item._mergePartial === 'string';
    }
    /**
     * Merge partials into configuration
     */
    async _mergePartials(mergeKey, workspacePath) {
        if (!this.hasMergePartial(mergeKey)) {
            return mergeKey;
        }
        let filePartial = '';
        if (mergeKey._mergePartial.startsWith('file://')) {
            filePartial = this.getEncodedDestinationPath(this.createPartialsRemoteCacheDir(workspacePath), mergeKey);
            const disablePartialCache = this.unifiedConfig.getInstanceSetting('dev.disablePartialCache');
            if (disablePartialCache || !fs.existsSync(filePartial)) {
                await fs.copy(mergeKey._mergePartial.substring(7), filePartial);
            }
        }
        else if (mergeKey._mergePartial.startsWith('http://') ||
            mergeKey._mergePartial.startsWith('https://')) {
            filePartial = this.getEncodedDestinationPath(this.createPartialsRemoteCacheDir(workspacePath), mergeKey);
            const disablePartialCache = this.unifiedConfig.getInstanceSetting('dev.disablePartialCache');
            if (disablePartialCache || !fs.existsSync(filePartial)) {
                await this._getRemotePartial(mergeKey._mergePartial, filePartial);
            }
        }
        else if (mergeKey._mergePartial.startsWith('dogfood_site://')) {
            const filePartialPattern = path.join(this.pathHelper.getApplicationResourcesDir(this.environmentInfo), 'all', 'dog_food_model', 'partials', mergeKey._mergePartial.slice(15) +
                '.{' +
                this.formatProviderResolver.allFormatsExt().join(',') +
                '}');
            const files = glob.sync(toGlobPath(filePartialPattern));
            if (files.length > 0) {
                filePartial = files[0];
            }
        }
        else {
            const filePartialPattern = path.join(workspacePath, 'quiqr', 'model', 'partials', mergeKey._mergePartial + '.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}');
            const files = glob.sync(toGlobPath(filePartialPattern));
            if (files.length > 0) {
                filePartial = files[0];
            }
        }
        if (filePartial && fs.existsSync(filePartial)) {
            if (!mergeKey._mergePartial.startsWith('dogfood_site://')) {
                this.parseInfo.partialFiles.push({ key: mergeKey.key, filename: filePartial });
            }
            const strData = await fs.readFile(filePartial, 'utf8');
            let formatProvider = this.formatProviderResolver.resolveForFilePath(filePartial);
            if (formatProvider == null) {
                formatProvider = this.formatProviderResolver.getDefaultFormat();
            }
            const mergeData = formatProvider.parse(strData);
            if (!isRecord(mergeData)) {
                throw new Error(`Invalid partial file format: ${filePartial}`);
            }
            // Merge partial data with base config
            // mergeKey (base config) takes precedence over mergeData (partial) for duplicate field keys
            const newData = deepmerge(mergeData, mergeKey);
            // REMOVE DUPLICATE FIELDS - PREFER FIELDS FROM BASE CONFIG OVER PARTIAL FIELDS
            // Both singleConfig and collectionConfig have optional fields arrays
            // If a field key exists in both, the base config version is kept
            const fields = newData.fields;
            if (fields && Array.isArray(fields)) {
                const typedFields = fields;
                const deduped = typedFields
                    .reverse()
                    .filter((field, index, self) => index === self.findIndex((t) => t.key === field.key));
                // RESTORE ORIGINAL ORDER
                newData.fields = deduped.reverse();
            }
            // ONLY WHEN MERGE WAS SUCCESSFUL DELETE THE KEY TO PREVENT ERROR.
            delete newData._mergePartial;
            return newData;
        }
        return mergeKey;
    }
    /**
     * Fetch remote partial from URL
     */
    async _getRemotePartial(url, destination) {
        try {
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Failed to fetch remote partial: ${response.status} ${response.statusText}`);
            }
            const data = await response.text();
            fs.writeFileSync(destination, data);
            return destination;
        }
        catch (err) {
            if (err instanceof Error) {
                console.log(`Error fetching remote partial from ${url}: ${err.message}`);
            }
            else {
                console.log('Unknown error fetching remote partial:', err);
            }
            throw err;
        }
    }
    /**
     * Get model parse information
     */
    getModelParseInfo() {
        return this.parseInfo;
    }
    getEnvironmentInfo() {
        return this.environmentInfo;
    }
}