All files / backend/src/services/configuration configuration-data-provider.ts

59.55% Statements 53/89
41.46% Branches 17/41
45.45% Functions 5/11
60.22% Lines 53/88

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                                                                                                                9x 9x 9x                             11x 11x     11x       11x     11x 11x     11x     11x   11x   11x 11x       11x   11x 11x   11x       11x 11x 11x     11x             11x                   11x                       11x     11x 11x             11x             11x             11x 11x   11x                               11x       11x     11x         11x 11x             11x       11x 11x 11x 11x   11x           11x                                   11x 11x 11x       11x           11x 11x 11x       11x         11x                        
/**
 * Configuration Data Provider
 *
 * Discovers, loads, and caches site configurations from the filesystem.
 * Handles automatic migrations for legacy configs and etalage data loading.
 *
 * Migrated from: backend/src-main/app-prefs-state/configuration-data-provider.js
 */
 
import fs from 'fs-extra';
import path from 'path';
import { glob } from 'glob';
import type { PathHelper } from '../../utils/path-helper.js';
import type { FormatProviderResolver } from '../../utils/format-provider-resolver.js';
import { isRecord } from '../../utils/format-providers/types.js';
import { siteConfigSchema } from '@quiqr/types/schemas';
import type { SiteConfig, Configurations } from '@quiqr/types';
 
/**
 * Extended site config with runtime properties added during loading
 */
export interface RuntimeSiteConfig extends SiteConfig {
  configPath: string;
  published: string;
}
 
/**
 * Etalage data structure (showcase metadata for a site)
 */
interface EtalageData {
  screenshots: string[];
  favicons: string[];
  [key: string]: unknown; // Allow additional properties from etalage.json
}
 
/**
 * Logger interface for output
 */
interface Logger {
  appendLine(message: string): void;
}
 
/**
 * ConfigurationDataProvider loads and caches site configurations
 */
export class ConfigurationDataProvider {
  private cache?: Configurations;
  private pathHelper: PathHelper;
  private formatResolver: FormatProviderResolver;
  private logger: Logger;
 
  constructor(
    pathHelper: PathHelper,
    formatResolver: FormatProviderResolver,
    logger: Logger
  ) {
    this.pathHelper = pathHelper;
    this.formatResolver = formatResolver;
    this.logger = logger;
  }
 
  /**
   * Invalidate the configuration cache
   */
  invalidateCache(): void {
    this.cache = undefined;
  }
 
  /**
   * Get all site configurations (async)
   * @param options - Optional invalidateCache flag
   */
  async getConfigurations(options: { invalidateCache?: boolean } = {}): Promise<Configurations> {
    Eif (options.invalidateCache) {
      this.cache = undefined;
    }
 
    Iif (this.cache) {
      return this.cache;
    }
 
    const root = this.pathHelper.getRoot();
 
    // Search patterns for site configs
    const sitePathPattern = path.join(root, 'sites', '*/config.json').replace(/\\/gi, '/');
    const oldSitePathPattern = path.join(root, 'config.*.json').replace(/\\/gi, '/');
 
    // Find all config files
    const files = [
      ...(await glob(sitePathPattern)),
      ...(await glob(oldSitePathPattern))
    ].map(x => path.normalize(x));
 
    const sites: RuntimeSiteConfig[] = [];
 
    for (const conffile of files) {
      Iif (!fs.existsSync(conffile)) {
        continue;
      }
 
      try {
        // Read and parse the config file
        const strData = fs.readFileSync(conffile, { encoding: 'utf-8' });
        const formatProvider = this.formatResolver.resolveForFilePath(conffile);
 
        Iif (!formatProvider) {
          throw new Error(`Could not resolve a format provider for file ${conffile}.`);
        }
 
        const site = formatProvider.parse(strData);
        const result = siteConfigSchema.safeParse(site);
        let needsMigration = false;
 
        // Migration: Ensure name field exists - use key as fallback
        Iif (result.success && !result.data.name) {
          result.data.name = result.data.key;
          needsMigration = true;
          this.logger.appendLine(`Migration: Added missing 'name' field to '${conffile}'`);
        }
 
        // Migration: Ensure source field exists - use default folder source
        Iif (result.success && !result.data.source) {
          result.data.source = {
            type: 'folder',
            path: 'main'
          };
          needsMigration = true;
          this.logger.appendLine(`Migration: Added missing 'source' field to '${conffile}'`);
        }
 
        // Save the migrated config back to disk
        Iif (needsMigration) {
          try {
            fs.writeFileSync(conffile, JSON.stringify(site, null, 2), { encoding: 'utf8' });
            this.logger.appendLine(`Migrated site config '${conffile}'`);
          } catch (writeErr) {
            this.logger.appendLine(
              `Warning: Could not save migrated config '${conffile}': ${writeErr instanceof Error ? writeErr.message : String(writeErr)}`
            );
          }
        }
 
        // Validate the site config with Zod
        const validatedSite = siteConfigSchema.parse(site);
 
        // Convert relative paths to absolute
        Eif (validatedSite.source) {
          validatedSite.source.path = this.siteSourceRelativeToAbsolute(
            validatedSite,
            conffile
          );
        }
 
        // Add runtime properties
        const runtimeSite: RuntimeSiteConfig = {
          ...validatedSite,
          published: 'unknown',
          configPath: conffile,
          etalage: this.getEtalage(validatedSite)
        };
 
        sites.push(runtimeSite);
      } catch (e) {
        const errorMsg = e instanceof Error ? e.message : String(e);
        this.logger.appendLine(`Configuration file is invalid '${conffile}': ${errorMsg}`);
      }
    }
 
    const configurations: Configurations = { sites };
    this.cache = configurations;
 
    return configurations;
  }
 
  /**
   * Get a single site configuration by key
   */
  async getSiteConfig(siteKey: string): Promise<RuntimeSiteConfig | null> {
    const configurations = await this.getConfigurations();
    const site = configurations.sites.find(s => s.key === siteKey);
    return site ? (site as RuntimeSiteConfig) : null;
  }
 
  /**
   * Convert relative site source paths to absolute paths
   */
  private siteSourceRelativeToAbsolute(site: SiteConfig, conffile: string): string {
    Iif (!site.source) {
      return '';
    }
 
    const sourcePath = site.source.path;
 
    // If path is already absolute (starts with /), return as-is
    Iif (sourcePath.substring(0, 1) === '/') {
      return sourcePath;
    }
 
    // Otherwise, resolve relative to site directory
    const siteKey = path.basename(path.dirname(conffile));
    return path.join(this.pathHelper.getRoot(), 'sites', siteKey, sourcePath);
  }
 
  /**
   * Load etalage data (showcase metadata) for a site
   */
  private getEtalage(site: SiteConfig): EtalageData {
    Iif (!site.source) {
      return { screenshots: [], favicons: [] };
    }
 
    const sourcePath = site.source.path;
    const etalagePath = path.join(sourcePath, 'quiqr/etalage/etalage.json');
    const etalageScreenshotsPath = path.join(sourcePath, 'quiqr/etalage/screenshots/');
    const etalageFaviconPath = path.join(sourcePath, 'quiqr/etalage/favicon/');
 
    let etalage: EtalageData = {
      screenshots: [],
      favicons: []
    };
 
    // Load etalage.json if it exists
    Iif (fs.existsSync(etalagePath)) {
      try {
        const strData = fs.readFileSync(etalagePath, { encoding: 'utf-8' });
        const formatProvider = this.formatResolver.resolveForFilePath(etalagePath);
        if (formatProvider) {
          const parsed = formatProvider.parse(strData);
          if (isRecord(parsed)) {
            etalage = { ...etalage, ...parsed };
          }
        }
      } catch (e) {
        this.logger.appendLine(
          `Warning: Could not load etalage.json for site: ${e instanceof Error ? e.message : String(e)}`
        );
      }
    }
 
    // Find screenshot files
    try {
      const screenshotPattern = path.join(etalageScreenshotsPath, '*.{png,jpg,jpeg,gif}').replace(/\\/gi, '/');
      const screenshotFiles = glob.sync(screenshotPattern).map(x => {
        const normalized = path.normalize(x);
        return normalized.substr(sourcePath.length);
      });
      etalage.screenshots = screenshotFiles;
    } catch {
      // Ignore glob errors (directory doesn't exist, etc.)
    }
 
    // Find favicon files
    try {
      const faviconPattern = path.join(etalageFaviconPath, '*.{png,jpg,jpeg,gif,ico}').replace(/\\/gi, '/');
      const faviconFiles = glob.sync(faviconPattern).map(x => {
        const normalized = path.normalize(x);
        return normalized.substr(sourcePath.length);
      });
      etalage.favicons = faviconFiles;
    } catch {
      // Ignore glob errors (directory doesn't exist, etc.)
    }
 
    return etalage;
  }
}
 
/**
 * Simple console logger adapter
 */
export class ConsoleLogger implements Logger {
  appendLine(message: string): void {
    console.log(message);
  }
}