All files / backend/dist/config container.js

0% Statements 0/79
0% Branches 0/21
0% Functions 0/14
0% Lines 0/77

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
/**
 * Dependency Injection Container
 *
 * Central container for all application dependencies.
 * Replaces scattered global variables with clean dependency injection.
 */
import { AppConfig } from './app-config.js';
import { AppState } from './app-state.js';
import { createUnifiedConfigService } from './unified-config-service.js';
import { PathHelper } from '../utils/path-helper.js';
import { FormatProviderResolver } from '../utils/format-provider-resolver.js';
import { ConfigurationDataProvider, ConsoleLogger } from '../services/configuration/index.js';
import { LibraryService } from '../services/library/library-service.js';
import { SyncFactory } from '../sync/sync-factory.js';
import { SiteSourceFactory } from '../site-sources/site-source-factory.js';
import { WorkspaceConfigProvider } from '../services/workspace/workspace-config-provider.js';
import { FolderImporter } from '../import/folder-importer.js';
import { GitImporter } from '../import/git-importer.js';
import { Pogozipper } from '../import/pogozipper.js';
import { Embgit } from '../embgit/embgit.js';
import { WorkspaceService } from '../services/workspace/workspace-service.js';
import { createModelWatcher } from '../services/workspace/model-watcher.js';
import { createScaffoldModelService } from '../services/scaffold-model/index.js';
import { BuildActionService } from '../build-actions/index.js';
import { ProviderFactory } from '../ssg-providers/provider-factory.js';
import { Logger } from '../logging/logger.js';
/**
 * Create the application container with all dependencies
 */
export function createContainer(options) {
    const { userDataPath, rootPath, adapters, configFileName } = options;
    // Create unified config service (new architecture)
    // Relies on hardcoded defaults for initial values
    const unifiedConfig = createUnifiedConfigService({ configDir: userDataPath });
    // Create legacy config and state (for backward compatibility)
    const config = new AppConfig(userDataPath, configFileName);
    const state = new AppState();
    // Create path helper with dynamic config getter
    // This ensures PathHelper always reads the current dataFolder from UnifiedConfigService
    const pathHelper = new PathHelper(adapters.appInfo, rootPath, () => ({
        dataFolder: unifiedConfig.getInstanceSetting('storage.dataFolder'),
        currentSitePath: state.currentSitePath,
    }));
    // Create format resolver
    const formatResolver = new FormatProviderResolver();
    // Create structured logger
    const structuredLogger = new Logger();
    // Create configuration provider with dependencies
    const logger = new ConsoleLogger();
    const configurationProvider = new ConfigurationDataProvider(pathHelper, formatResolver, logger);
    // Create factories
    const syncFactory = new SyncFactory();
    const siteSourceFactory = new SiteSourceFactory(pathHelper);
    // Initialize syncFactory with dependencies (will be set after configurationProvider is created)
    // This is done below after all dependencies are available
    // Create environment info from platform
    const environmentInfo = {
        platform: process.platform === 'darwin' ? 'macOS' :
            process.platform === 'win32' ? 'windows' :
                'linux',
        isPackaged: adapters.appInfo.isPackaged(),
    };
    // Create provider factory for SSG providers
    const providerFactory = new ProviderFactory({
        pathHelper,
        environmentInfo,
        outputConsole: adapters.outputConsole,
        windowAdapter: adapters.window,
        shellAdapter: adapters.shell,
        appConfig: config,
    });
    // Create workspace config provider
    const workspaceConfigProvider = new WorkspaceConfigProvider(formatResolver, pathHelper, unifiedConfig, environmentInfo);
    // Create model change event broadcaster for SSE notifications
    const modelChangeSubscribers = new Set();
    const modelChangeEventBroadcaster = {
        emit: (event) => {
            modelChangeSubscribers.forEach((cb) => cb(event));
        },
        subscribe: (callback) => {
            modelChangeSubscribers.add(callback);
            return () => {
                modelChangeSubscribers.delete(callback);
            };
        },
    };
    // Create the container object first (needed for circular dependency)
    const container = {
        config,
        unifiedConfig,
        state,
        adapters,
        pathHelper,
        formatResolver,
        configurationProvider,
        providerFactory,
        syncFactory,
        siteSourceFactory,
        workspaceConfigProvider,
        environmentInfo,
        modelChangeEventBroadcaster,
        logger: structuredLogger,
    };
    // Create library service with container dependency
    const libraryService = new LibraryService(container);
    container.libraryService = libraryService;
    // Create folder importer with all dependencies
    const folderImporter = new FolderImporter(pathHelper, formatResolver, libraryService, workspaceConfigProvider);
    container.folderImporter = folderImporter;
    // Create embgit with dependencies
    const embgit = new Embgit(pathHelper, adapters.outputConsole, adapters.appInfo, rootPath, environmentInfo);
    container.embgit = embgit;
    // Create git importer with dependencies
    const gitImporter = new GitImporter(embgit, pathHelper, formatResolver, libraryService);
    container.gitImporter = gitImporter;
    // Create pogozipper with dependencies
    const pogozipper = new Pogozipper(pathHelper, libraryService, adapters.dialog, adapters.window);
    container.pogozipper = pogozipper;
    // Initialize syncFactory with dependencies
    syncFactory.setDependencies({
        pathHelper,
        outputConsole: adapters.outputConsole,
        windowAdapter: adapters.window,
        configurationProvider,
        embgit,
        container,
    });
    // Initialize providerFactory with container reference (breaks circular dependency)
    providerFactory.setContainer(container);
    // Create BuildActionService (uses outputConsole for logging and container for structured logging)
    const buildActionService = new BuildActionService(adapters.outputConsole, container);
    // Create WorkspaceService factory
    // Note: OutputConsole and ScreenshotWindowManager are provided by Electron runtime
    container.createWorkspaceService = (workspacePath, workspaceKey, siteKey) => {
        const dependencies = {
            workspaceConfigProvider,
            formatProviderResolver: formatResolver,
            pathHelper,
            appConfig: config,
            appState: state,
            providerFactory,
            windowAdapter: adapters.window,
            shellAdapter: adapters.shell,
            outputConsole: adapters.outputConsole,
            screenshotWindowManager: adapters.screenshotWindowManager,
            buildActionService,
            container,
        };
        return new WorkspaceService(workspacePath, workspaceKey, siteKey, dependencies);
    };
    // Cache for the current WorkspaceService (needed for Hugo server persistence)
    let cachedWorkspaceService;
    let cachedWorkspaceKey;
    let cachedSiteKey;
    let currentModelWatcher;
    // Helper to get WorkspaceService (common pattern used across handlers)
    container.getWorkspaceService = async (siteKey, workspaceKey) => {
        // Import SiteService dynamically to avoid circular dependency
        const { SiteService } = await import('../services/site/site-service.js');
        // Get site configuration
        const siteConfig = await libraryService.getSiteConf(siteKey);
        // Create SiteService instance
        const siteService = new SiteService(siteConfig, siteSourceFactory, syncFactory);
        // Handle special workspace keys that should resolve to the default workspace
        let resolvedWorkspaceKey = workspaceKey;
        if (workspaceKey === 'source' || workspaceKey === 'default') {
            // Resolve to the first available workspace
            const workspaces = await siteService.listWorkspaces();
            if (workspaces.length === 0) {
                throw new Error(`No workspaces found for site: ${siteKey}`);
            }
            resolvedWorkspaceKey = workspaces[0].key;
        }
        // Return cached instance if it matches the requested workspace
        if (cachedWorkspaceService &&
            cachedSiteKey === siteKey &&
            cachedWorkspaceKey === resolvedWorkspaceKey) {
            return cachedWorkspaceService;
        }
        // Stop Hugo server and model watcher from the old workspace before switching
        if (cachedWorkspaceService) {
            cachedWorkspaceService.stopHugoServer();
        }
        if (currentModelWatcher) {
            await currentModelWatcher.stop();
            currentModelWatcher = undefined;
        }
        // Get workspace head to find the path
        const workspaceHead = await siteService.getWorkspaceHead(resolvedWorkspaceKey);
        if (!workspaceHead) {
            throw new Error(`Workspace not found: ${resolvedWorkspaceKey} for site: ${siteKey}`);
        }
        // Create WorkspaceService and cache it
        const workspaceService = container.createWorkspaceService(workspaceHead.path, resolvedWorkspaceKey, siteKey);
        cachedWorkspaceService = workspaceService;
        cachedSiteKey = siteKey;
        cachedWorkspaceKey = resolvedWorkspaceKey;
        // Start model watcher for the new workspace
        currentModelWatcher = createModelWatcher({
            workspacePath: workspaceHead.path,
            workspaceConfigProvider,
            onCacheCleared: () => {
                container.modelChangeEventBroadcaster.emit({
                    type: 'model-cache-cleared',
                    siteKey,
                    workspaceKey: resolvedWorkspaceKey,
                });
            },
        });
        return workspaceService;
    };
    // Get the currently cached WorkspaceService
    container.getCurrentWorkspaceService = () => {
        return cachedWorkspaceService;
    };
    // Helper to get ScaffoldModelService
    container.getScaffoldModelService = async (siteKey, workspaceKey) => {
        // First get the workspace service to ensure we have a valid workspace path
        const workspaceService = await container.getWorkspaceService(siteKey, workspaceKey);
        // Create and return a ScaffoldModelService instance
        return createScaffoldModelService(workspaceService.getWorkspacePath(), {
            dialogAdapter: adapters.dialog,
            formatResolver,
        });
    };
    // Backward compatibility accessors (deprecated)
    Object.defineProperty(container, 'hugoDownloader', {
        get: async () => {
            const provider = await providerFactory.getProvider('hugo');
            return provider.getBinaryManager();
        },
        enumerable: false,
    });
    Object.defineProperty(container, 'hugoUtils', {
        get: async () => {
            const provider = await providerFactory.getProvider('hugo');
            return {
                createSiteDir: (directory, title, configFormat) => provider.createSite({ directory, title, configFormat }),
            };
        },
        enumerable: false,
    });
    return container;
}