All files / backend/src/services/workspace initial-workspace-config-builder.ts

0% Statements 0/37
0% Branches 0/14
0% Functions 0/9
0% Lines 0/37

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Initial Workspace Config Builder
 *
 * Creates initial Quiqr configuration files for new or unconfigured workspaces.
 */
 
import path from 'path';
import fs from 'fs-extra';
import type { FormatProvider } from '../../utils/format-providers/types.js';
import { FormatProviderResolver } from '../../utils/format-provider-resolver.js';
import type { PathHelper } from '../../utils/path-helper.js';
import { BuildConfig, MenuItem, ServeConfig } from '@quiqr/types';
 
/**
 * Represents parsed Hugo configuration data.
 * We only need to access the keys, so this is a record with string keys.
 */
type HugoConfigData = Record<string, unknown>;
 
/** Menu section in the initial config */
interface InitialMenuSection {
  key: string;
  title: string;
  menuItems: MenuItem[];
}
 
/** Field definition for initial singles */
interface InitialSingleField {
  key: string;
  title: string;
  type: string;
  tip: string;
}
 
/** Single content item in initial config */
interface InitialSingle {
  key: string;
  title: string;
  file: string;
  fields: InitialSingleField[];
}
 
/** The complete initial base configuration structure */
interface InitialBaseConfig {
  ssgType: string;
  ssgVersion: string;
  serve: ServeConfig[];
  build: BuildConfig[];
  menu: InitialMenuSection[];
  collections: never[];
  singles: InitialSingle[];
}
 
/** Field definition for partials config (simplified) */
interface PartialsField {
  key: string;
  type: string;
  content?: string;
  title?: string;
  default?: string;
  path?: string;
  extensions?: string[];
  multiLine?: boolean;
  fields?: PartialsField[];
}
 
/** Partials configuration structure */
interface PartialsConfig {
  dataformat: string;
  fields: PartialsField[];
}
 
/** Include configuration item */
interface IncludeConfigItem {
  key: string;
  title: string;
  folder: string;
  extension: string;
  itemtitle: string;
  _mergePartial: string;
}
 
/** Options for building the config */
interface GetConfigOptions {
  ssgType: string;
  ssgVersion: string;
  configFile: string;
  ext: string;
  hugoConfigData: HugoConfigData;
}
 
/**
 * InitialWorkspaceConfigBuilder creates default configuration files
 * for workspaces that don't have Quiqr configuration yet
 */
export class InitialWorkspaceConfigBuilder {
  private workspacePath: string;
  private formatProviderResolver: FormatProviderResolver;
  private pathHelper: PathHelper;
 
  constructor(
    workspacePath: string,
    formatProviderResolver: FormatProviderResolver,
    pathHelper: PathHelper
  ) {
    this.workspacePath = workspacePath;
    this.formatProviderResolver = formatProviderResolver;
    this.pathHelper = pathHelper;
  }
 
  /**
   * Build all initial configuration files
   * @param ssgType - SSG type (e.g., 'hugo', 'eleventy')
   * @param ssgVersion - SSG version to use
   * @returns Path to the created base config file
   */
  buildAll(ssgType: string = 'hugo', ssgVersion: string = '0.88.1'): string {
    this.buildHomeReadme();
 
    const { dataBase, formatProvider } = this.buildBase(ssgType, ssgVersion);
 
    fs.ensureDirSync(path.join(this.workspacePath, 'quiqr', 'model'));
    fs.ensureDirSync(path.join(this.workspacePath, 'quiqr', 'model', 'includes'));
    fs.ensureDirSync(path.join(this.workspacePath, 'quiqr', 'model', 'partials'));
 
    const filePathBase = path.join(
      this.workspacePath,
      'quiqr',
      'model',
      'base.' + formatProvider.defaultExt()
    );
 
    fs.writeFileSync(filePathBase, formatProvider.dump(dataBase));
 
    return filePathBase;
  }
 
  /**
   * Get the default configuration object
   */
  private getConfig(opts: GetConfigOptions): InitialBaseConfig {
    const rootKeysLower: Record<string, string> = {};
    Object.keys(opts.hugoConfigData).forEach((key) => {
      rootKeysLower[key.toLowerCase()] = key;
    });
 
    const getBestKey = (key: string): string => {
      return rootKeysLower[key.toLowerCase()] || key;
    };
 
    return {
      ssgType: opts.ssgType || 'hugo',
      ssgVersion: opts.ssgVersion || '',
      serve: [{ key: 'default', config: opts.configFile }],
      build: [{ key: 'default', config: opts.configFile }],
      menu: [
        {
          key: 'settings',
          title: 'Settings',
          menuItems: [{ key: 'mainConfig' }],
        },
      ],
      collections: [],
      singles: [
        {
          key: 'mainConfig',
          title: 'Site Configuration',
          file: `${opts.configFile}`,
          fields: [
            {
              key: getBestKey('title'),
              title: 'Site Title',
              type: 'string',
              tip: 'Your page title.',
            },
            {
              key: getBestKey('baseURL'),
              title: 'Base URL',
              type: 'string',
              tip: 'Your site URL.',
            },
          ],
        },
      ],
    };
  }
 
  /**
   * Build default partials configuration
   */
  buildPartials(): PartialsConfig {
    return {
      dataformat: 'yaml',
      fields: [
        {
          key: 'info',
          type: 'info',
          content: '# Info\nYou can write custom instructions here.',
        },
        { key: 'title', title: 'Title', type: 'string' },
        { key: 'mainContent', title: 'Content', type: 'markdown' },
        { key: 'pubdate', title: 'Pub Date', type: 'date', default: 'now' },
        { key: 'draft', title: 'Draft', type: 'boolean' },
        {
          key: 'bundle-manager',
          type: 'bundle-manager',
          path: 'imgs',
          extensions: ['png', 'jpg', 'gif'],
          fields: [
            { key: 'title', title: 'Title', type: 'string' },
            { key: 'description', title: 'Description', type: 'string', multiLine: true },
          ],
        },
      ],
    };
  }
 
  /**
   * Build default includes configuration
   */
  buildInclude(): IncludeConfigItem[] {
    return [
      {
        key: 'pages',
        title: 'Other Pages',
        folder: 'content/page/',
        extension: 'md',
        itemtitle: 'Page',
        _mergePartial: 'page',
      },
    ];
  }
 
  /**
   * Build base configuration
   */
  private buildBase(ssgType: string, ssgVersion: string): {
    formatProvider: FormatProvider;
    dataBase: InitialBaseConfig;
  } {
    let hugoConfigPath = this.pathHelper.hugoConfigFilePath(this.workspacePath);
    let formatProvider: FormatProvider;
 
    if (hugoConfigPath == null) {
      hugoConfigPath = path.join(
        this.workspacePath,
        'config.' + this.formatProviderResolver.getDefaultFormatExt()
      );
      formatProvider = this.formatProviderResolver.getDefaultFormat();
      const minimalConfigStr = formatProvider.dump({
        title: 'New Site Title',
        baseURL: 'http://newsite.com',
      });
      fs.writeFileSync(hugoConfigPath, minimalConfigStr, 'utf-8');
    } else {
      const resolved = this.formatProviderResolver.resolveForFilePath(hugoConfigPath);
      if (!resolved) {
        throw new Error('Could not resolve a FormatProvider.');
      }
      formatProvider = resolved;
    }
 
    const hugoConfigData = formatProvider.parse(fs.readFileSync(hugoConfigPath, 'utf-8')) as HugoConfigData;
    const relHugoConfigPath = path.relative(this.workspacePath, hugoConfigPath);
 
    const dataBase = this.getConfig({
      configFile: relHugoConfigPath,
      ext: formatProvider.defaultExt(),
      ssgType,
      ssgVersion,
      hugoConfigData,
    });
 
    return { formatProvider, dataBase };
  }
 
  /**
   * Build home README file
   */
  private buildHomeReadme(): void {
    const readmePath = path.join(this.workspacePath, 'quiqr', 'home', 'index.md');
    if (!fs.existsSync(readmePath)) {
      fs.ensureDirSync(path.join(this.workspacePath, 'quiqr', 'home'));
      fs.writeFileSync(
        readmePath,
        `
# README FOR NEW SITE
 
If you're a website developer you can read the [Quiqr Site Developer
Docs](https://book.quiqr.org/)
how to customize your Site Admin.
 
Quiqr is a Desktop App made for [Hugo](https://gohugo.io). Read all about
[creating Hugo websites](https://gohugo.io/getting-started/quick-start/).
 
To change this about text, edit this file: *${readmePath}*.
 
Happy Creating.
 
❤️ Quiqr
        `.trim()
      );
    }
  }
}