File size: 6,110 Bytes
34367da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// DataSourceConfigManager - Manage which data sources are enabled/disabled
import { promises as fs } from 'fs';
import * as path from 'path';
import { projectMemory } from '../project/ProjectMemory.js';

export interface DataSourceConfig {
    name: string;
    enabled: boolean;
    requiresApproval: boolean;  // If true, user must approve before first use
    approved: boolean;          // Has user approved this source?
    lastUsed?: string;
    description?: string;
}

export class DataSourceConfigManager {
    private configPath: string;
    private config: Map<string, DataSourceConfig> = new Map();

    constructor(configPath?: string) {
        this.configPath = configPath || path.join(process.cwd(), 'apps', 'backend', 'data', 'datasource-config.json');
    }

    /**

     * Load configuration from disk

     */
    async load(): Promise<void> {
        try {
            const data = await fs.readFile(this.configPath, 'utf-8');
            const configs = JSON.parse(data) as DataSourceConfig[];

            this.config.clear();
            configs.forEach(cfg => {
                this.config.set(cfg.name, cfg);
            });

            console.log(`πŸ“‹ Loaded data source config: ${this.config.size} sources`);
        } catch (error: any) {
            if (error.code === 'ENOENT') {
                console.log('πŸ“‹ No existing config found, creating new one');
                await this.save();
            } else {
                console.error('Failed to load data source config:', error);
            }
        }
    }

    /**

     * Save configuration to disk

     */
    async save(): Promise<void> {
        try {
            const configs = Array.from(this.config.values());
            const dir = path.dirname(this.configPath);

            // Ensure directory exists
            try {
                await fs.mkdir(dir, { recursive: true });
            } catch { }

            await fs.writeFile(this.configPath, JSON.stringify(configs, null, 2));
            console.log('πŸ’Ύ Saved data source configuration');
        } catch (error) {
            console.error('Failed to save data source config:', error);
        }
    }

    /**

     * Register a new data source (requires approval by default)

     */
    async registerSource(name: string, description?: string, requiresApproval: boolean = true): Promise<boolean> {
        if (this.config.has(name)) {
            // Already registered
            return this.isEnabled(name);
        }

        const config: DataSourceConfig = {
            name,
            enabled: false, // Disabled by default
            requiresApproval,
            approved: !requiresApproval, // If no approval required, mark as approved
            description
        };

        this.config.set(name, config);
        await this.save();

        // Log to Project Memory
        projectMemory.logLifecycleEvent({
            eventType: 'other',
            status: 'in_progress',
            details: {
                type: 'new_datasource_registered',
                name,
                description,
                requiresApproval,
                message: requiresApproval
                    ? `⚠️ New data source "${name}" requires user approval before use`
                    : `βœ… New data source "${name}" registered and ready`
            }
        });

        console.log(`πŸ“Œ Registered new data source: ${name} (approval required: ${requiresApproval})`);

        return !requiresApproval; // Return true if can be used immediately
    }

    /**

     * Enable/disable a data source

     */
    async setEnabled(name: string, enabled: boolean): Promise<void> {
        const config = this.config.get(name);
        if (!config) {
            throw new Error(`Unknown data source: ${name}`);
        }

        config.enabled = enabled;
        await this.save();

        console.log(`${enabled ? 'βœ…' : '❌'} Data source "${name}" ${enabled ? 'enabled' : 'disabled'}`);
    }

    /**

     * Approve a data source for use

     */
    async approve(name: string): Promise<void> {
        const config = this.config.get(name);
        if (!config) {
            throw new Error(`Unknown data source: ${name}`);
        }

        config.approved = true;
        config.enabled = true; // Auto-enable when approved
        await this.save();

        projectMemory.logLifecycleEvent({
            eventType: 'other',
            status: 'success',
            details: {
                type: 'datasource_approved',
                name,
                message: `βœ… User approved data source: ${name}`
            }
        });

        console.log(`βœ… Approved and enabled data source: ${name}`);
    }

    /**

     * Check if a data source is enabled and approved

     */
    isEnabled(name: string): boolean {
        const config = this.config.get(name);
        if (!config) return false;

        return config.enabled && config.approved;
    }

    /**

     * Get all sources that require approval

     */
    getPendingApprovals(): DataSourceConfig[] {
        return Array.from(this.config.values())
            .filter(cfg => cfg.requiresApproval && !cfg.approved);
    }

    /**

     * Get all enabled sources

     */
    getEnabledSources(): string[] {
        return Array.from(this.config.values())
            .filter(cfg => this.isEnabled(cfg.name))
            .map(cfg => cfg.name);
    }

    /**

     * Get all sources

     */
    getAllSources(): DataSourceConfig[] {
        return Array.from(this.config.values());
    }

    /**

     * Mark source as used

     */
    async markUsed(name: string): Promise<void> {
        const config = this.config.get(name);
        if (config) {
            config.lastUsed = new Date().toISOString();
            await this.save();
        }
    }
}

// Singleton instance
export const dataSourceConfig = new DataSourceConfigManager();