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 | 53x 9x 9x 9x 9x 9x 9x 9x 9x 13x 13x 13x 13x 13x 13x 5x 5x 8x 8x 8x 8x 8x 13x 13x 13x 13x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 14x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 14x 14x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 24x 24x 24x 24x 14x 14x 14x | /**
* 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: string): string {
return p.replace(/\\/g, '/');
}
import { isRecord } from '../../utils/format-providers/types.js';
import { FormatProviderResolver } from '../../utils/format-provider-resolver.js';
import { WorkspaceConfigValidator, type WorkspaceConfig } from './workspace-config-validator.js';
import { InitialWorkspaceConfigBuilder } from './initial-workspace-config-builder.js';
import { FileCacheToken } from './file-cache-token.js';
import type { PathHelper, EnvironmentInfo } from '../../utils/path-helper.js';
import type { UnifiedConfigService } from '../../config/unified-config-service.js';
import {
type MergeableConfigItem,
type PartialWorkspaceConfig,
type MenuConfig,
type Field,
} from '@quiqr/types';
/**
* Parse information - tracks which files were used to build the config
*/
export interface ParseInfo {
baseFile: string;
includeFiles: Array<{ key: string; filename: string }>;
includeFilesSub: Array<{ key: string; filename: string }>;
partialFiles: Array<{ key: string; filename: string }>;
}
/**
* Cache entry for workspace configurations
*/
interface CacheEntry {
token: FileCacheToken;
config: WorkspaceConfig;
}
/**
* WorkspaceConfigProvider loads and manages workspace configuration
* Uses dependency injection instead of global state
*/
export class WorkspaceConfigProvider {
private cache: Record<string, CacheEntry> = {};
private parseInfo: ParseInfo = {
baseFile: '',
includeFiles: [],
includeFilesSub: [],
partialFiles: [],
};
private formatProviderResolver: FormatProviderResolver;
private pathHelper: PathHelper;
private unifiedConfig: UnifiedConfigService;
private environmentInfo: EnvironmentInfo;
constructor(
formatProviderResolver: FormatProviderResolver,
pathHelper: PathHelper,
unifiedConfig: UnifiedConfigService,
environmentInfo: EnvironmentInfo
) {
this.formatProviderResolver = formatProviderResolver;
this.pathHelper = pathHelper;
this.unifiedConfig = unifiedConfig;
this.environmentInfo = environmentInfo;
}
/**
* Clear the configuration cache
*/
clearCache(): void {
this.cache = {};
this.parseInfo = {
baseFile: '',
includeFiles: [],
includeFilesSub: [],
partialFiles: [],
};
}
/**
* Read or create minimal model config for a workspace
*/
async readOrCreateMinimalModelConfig(
workspacePath: string,
workspaceKey: string
): Promise<WorkspaceConfig> {
let filePath = this.getQuiqrModelBasePath(workspacePath);
this.parseInfo.baseFile = filePath || '';
let token: FileCacheToken;
if (filePath != null) {
const cached = this.cache[filePath];
token = await new FileCacheToken([filePath]).build();
if (cached != null) {
Eif (await cached.token.match(token)) {
// can be reused
return cached.config;
}
}
} else E{
// 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: WorkspaceConfig = 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: string): string | undefined {
const fileExpPrimary = path.join(
workspacePath,
'quiqr',
'model',
'base.{' + this.formatProviderResolver.allFormatsExt().join(',') + '}'
);
const primaryFiles = glob.sync(toGlobPath(fileExpPrimary));
Eif (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
*/
private async _loadConfigurationsData(
filePath: string,
workspaceKey: string,
workspacePath: string
): Promise<WorkspaceConfig> {
const strData = fs.readFileSync(filePath, 'utf8');
let formatProvider = this.formatProviderResolver.resolveForFilePath(filePath);
Iif (formatProvider == null) {
formatProvider = this.formatProviderResolver.getDefaultFormat();
}
const dataPhase1Parse = formatProvider.parse(strData);
Iif (!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 as Partial<WorkspaceConfig>);
Iif (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 as WorkspaceConfig;
}
/**
* Ensure config object has required structure
* Builds a PartialWorkspaceConfig with defaults for missing arrays
*/
private configObjectSkeleton(configOrg: Record<string, unknown>): PartialWorkspaceConfig {
return {
...configOrg,
menu: Array.isArray(configOrg.menu) ? (configOrg.menu as MenuConfig) : [],
collections: Array.isArray(configOrg.collections)
? (configOrg.collections as MergeableConfigItem[])
: [],
singles: Array.isArray(configOrg.singles)
? (configOrg.singles as MergeableConfigItem[])
: [],
dynamics: Array.isArray(configOrg.dynamics)
? (configOrg.dynamics as MergeableConfigItem[])
: [],
};
}
/**
* Post-process config object: load includes and merge partials
*/
private async _postProcessConfigObject(
configOrg: Record<string, unknown>,
workspacePath: string
): Promise<PartialWorkspaceConfig> {
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
Iif (config.menu.length < 1) delete (config as Partial<PartialWorkspaceConfig>).menu;
Iif (config.collections.length < 1) delete (config as Partial<PartialWorkspaceConfig>).collections;
Eif (config.singles.length < 1) delete (config as Partial<PartialWorkspaceConfig>).singles;
Eif (config.dynamics.length < 1) delete (config as Partial<PartialWorkspaceConfig>).dynamics;
return config;
}
/**
* Get merge partial result
*/
async getMergePartialResult(
mergeKey: MergeableConfigItem,
workspacePath: string
): Promise<MergeableConfigItem> {
const result = await this._mergePartials(mergeKey, workspacePath);
return result;
}
/**
* Get remote partials cache directory
*/
partialRemoteCacheDir(workspacePath: string): string {
return path.join(workspacePath, 'quiqr', 'model', 'partialsRemoteCache');
}
/**
* Create remote partials cache directory
*/
createPartialsRemoteCacheDir(workspacePath: string): string {
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)
*/
private _loadIncludes(
configObject: PartialWorkspaceConfig,
fileIncludes: string,
showInParseInfo: boolean
): PartialWorkspaceConfig {
const files = glob.sync(toGlobPath(fileIncludes));
const newObject: Record<string, unknown> = {};
// 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);
Iif (formatProvider == null) {
formatProvider = this.formatProviderResolver.getDefaultFormat();
}
const mergeData = formatProvider.parse(strData);
const key = path.parse(filename).name;
Eif (showInParseInfo) {
this.parseInfo.includeFiles.push({ key, filename });
}
// Handle array includes (collections.yaml, singles.yaml, menu.yaml, dynamics.yaml)
Eif (Array.isArray(mergeData) && arrayKeys.includes(key)) {
const existingArray = configObject[key];
if (Array.isArray(existingArray)) {
// Concatenate with existing array
newObject[key] = [...existingArray, ...mergeData];
} else E{
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)
*/
private _loadIncludesSub(
modelType: keyof Pick<PartialWorkspaceConfig, 'singles' | 'collections' | 'menu'>,
configObject: PartialWorkspaceConfig,
fileIncludes: string,
showInParseInfo: boolean
): PartialWorkspaceConfig {
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 as MenuConfig[number]);
} else {
// Singles and collections are MergeableConfigItem objects
newObject[modelType].push(mergeDataSub as MergeableConfigItem);
}
});
return newObject;
}
/**
* Get encoded destination path for remote partials
*/
getEncodedDestinationPath(
filePartialDir: string,
mergeKey: MergeableConfigItem & { _mergePartial: string }
): string {
const encodeFilename = encodeURIComponent(mergeKey._mergePartial);
return path.join(filePartialDir, encodeFilename);
}
/**
* Type guard to check if a config item has _mergePartial property
*/
private hasMergePartial(
item: MergeableConfigItem
): item is MergeableConfigItem & { _mergePartial: string } {
return '_mergePartial' in item && typeof item._mergePartial === 'string';
}
/**
* Merge partials into configuration
*/
private async _mergePartials(
mergeKey: MergeableConfigItem,
workspacePath: string
): Promise<MergeableConfigItem> {
Eif (!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') as boolean;
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') as boolean;
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) as MergeableConfigItem;
// 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 as Field[];
const deduped = typedFields
.reverse()
.filter(
(field: Field, index: number, self: Field[]) =>
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
*/
private async _getRemotePartial(url: string, destination: string): Promise<string> {
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(): ParseInfo {
return this.parseInfo;
}
getEnvironmentInfo(): EnvironmentInfo {
return this.environmentInfo;
}
}
|