@mohammadhprp/system-prompt 0.13.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/installer.js DELETED
@@ -1,653 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- import { dirname, relative, resolve, isAbsolute } from 'node:path';
3
- import { mkdir, writeFile, readdir, stat, lstat, readFile, rm } from 'node:fs/promises';
4
- import { createHash } from 'node:crypto';
5
-
6
- import { categories } from './catalog.js';
7
- import { loadMcpConfigs, generateOpenCodeConfig, generateTuiConfig } from './agent-configs.js';
8
- import { LOCK_CATEGORIES, isFileBased, isCopyable, itemSourcePath, itemRelativePath, targetSubdir } from './item-layout.js';
9
-
10
- const __dirname = dirname(fileURLToPath(import.meta.url));
11
- const packageRoot = resolve(__dirname, '..');
12
-
13
- const AGENTS_MD = `# AGENTS.md
14
-
15
- Behavioral guidelines to reduce common LLM coding mistakes. Merge with project-specific instructions as needed.
16
-
17
- Read CONTEXT.md for repository-specific setup, commands, architecture, tests, and workflow guidance.
18
-
19
- **Tradeoff:** These guidelines bias toward caution over speed. For trivial tasks, use judgment.
20
-
21
- ## 1. Think Before Coding
22
-
23
- **Don't assume. Don't hide confusion. Surface tradeoffs.**
24
-
25
- Before implementing:
26
- - State your assumptions explicitly. If uncertain, ask.
27
- - If multiple interpretations exist, present them - don't pick silently.
28
- - If a simpler approach exists, say so. Push back when warranted.
29
- - If something is unclear, stop. Name what's confusing. Ask.
30
-
31
- ## 2. Simplicity First
32
-
33
- **Minimum code that solves the problem. Nothing speculative.**
34
-
35
- - No features beyond what was asked.
36
- - No abstractions for single-use code.
37
- - No "flexibility" or "configurability" that wasn't requested.
38
- - No error handling for impossible scenarios.
39
- - If you write 200 lines, and it could be 50, rewrite it.
40
-
41
- Ask yourself: "Would a senior engineer say this is overcomplicated?" If yes, simplify.
42
-
43
- ## 3. Surgical Changes
44
-
45
- **Touch only what you must. Clean up only your own mess.**
46
-
47
- When editing existing code:
48
- - Don't "improve" adjacent code, comments, or formatting.
49
- - Don't refactor things that aren't broken.
50
- - Match existing style, even if you'd do it differently.
51
- - If you notice unrelated dead code, mention it - don't delete it.
52
-
53
- When your changes create orphans:
54
- - Remove imports/variables/functions that YOUR changes made unused.
55
- - Don't remove pre-existing dead code unless asked.
56
-
57
- The test: Every changed line should trace directly to the user's request.
58
-
59
- ## 4. Goal-Driven Execution
60
-
61
- **Define success criteria. Loop until verified.**
62
-
63
- Transform tasks into verifiable goals:
64
- - "Add validation" → "Write tests for invalid inputs, then make them pass"
65
- - "Fix the bug" → "Write a test that reproduces it, then make it pass"
66
- - "Refactor X" → "Ensure tests pass before and after"
67
-
68
- For multistep tasks, state a brief plan:
69
-
70
- 1. [Step] → verify: [check]
71
- 2. [Step] → verify: [check]
72
- 3. [Step] → verify: [check]
73
-
74
-
75
- Strong success criteria let you loop independently. Weak criteria ("make it work") require constant clarification.
76
-
77
- ---
78
-
79
- **These guidelines are working if:** fewer unnecessary changes in diffs, fewer rewrites due to overcomplication, and clarifying questions come before implementation rather than after mistakes.
80
-
81
- `;
82
-
83
- const OPENCODE_GITIGNORE = `.env*
84
- node_modules
85
- package.json
86
- package-lock.json
87
- bun.lock
88
- `;
89
-
90
- export const LOCK_VERSION = 1;
91
-
92
- export function lockToSelections(lock) {
93
- const selections = {};
94
- if (!lock) return selections;
95
- for (const category of LOCK_CATEGORIES) {
96
- const ids = Object.keys(lock[category] || {});
97
- if (ids.length) selections[category] = ids;
98
- }
99
- return selections;
100
- }
101
-
102
- function buildComputedHash(files, fallbackId) {
103
- const keys = Object.keys(files).sort();
104
- if (keys.length === 0) return hash(fallbackId);
105
- if (keys.length === 1) return files[keys[0]];
106
- return hash(keys.map(path => `${path}:${files[path]}`).join('\n'));
107
- }
108
-
109
- function getExpectedHash(oldLock, relativePath) {
110
- const generated = oldLock?.generated?.[relativePath]?.computedHash;
111
- if (generated) return generated;
112
- for (const category of LOCK_CATEGORIES) {
113
- const entries = oldLock?.[category];
114
- if (!entries) continue;
115
- for (const entry of Object.values(entries)) {
116
- const value = entry?.files?.[relativePath];
117
- if (value) return value;
118
- }
119
- }
120
- return undefined;
121
- }
122
- export async function getPackageVersion() {
123
- try {
124
- const pkg = JSON.parse(await readFile(resolve(packageRoot, 'package.json'), 'utf-8'));
125
- return pkg.version || '0.0.0';
126
- } catch {
127
- return '0.0.0';
128
- }
129
- }
130
-
131
- export async function loadLockFile(absTarget) {
132
- try {
133
- const content = await readFile(resolve(absTarget, 'system-prompt-lock.json'), 'utf-8');
134
- const lock = JSON.parse(content);
135
- validateLock(lock);
136
- return lock;
137
- } catch (error) {
138
- if (error.code === 'ENOENT') return null;
139
- if (error instanceof SyntaxError || error.message?.startsWith('Invalid system-prompt lock')) {
140
- throw new Error(`${error.message}. Remove or repair system-prompt-lock.json before reinstalling.`);
141
- }
142
- throw error;
143
- }
144
- }
145
-
146
- function validateLock(lock) {
147
- if (!lock || typeof lock !== 'object' || Array.isArray(lock)) {
148
- throw new Error('Invalid system-prompt lock: expected an object');
149
- }
150
- if (lock.selections !== undefined || lock.managedFiles !== undefined) {
151
- throw new Error('Invalid system-prompt lock: legacy lock format no longer supported');
152
- }
153
- if (lock.version !== LOCK_VERSION) {
154
- throw new Error('Invalid system-prompt lock: unsupported version');
155
- }
156
- if (typeof lock.agentType !== 'string' || typeof lock.installedAt !== 'string') {
157
- throw new Error('Invalid system-prompt lock: missing installation metadata');
158
- }
159
- if (typeof lock.includeAgentsMd !== 'boolean') {
160
- throw new Error('Invalid system-prompt lock: includeAgentsMd must be a boolean');
161
- }
162
- const allowed = new Set(['version', 'agentType', 'installedAt', 'includeAgentsMd', 'generated', ...LOCK_CATEGORIES]);
163
- for (const key of Object.keys(lock)) {
164
- if (!allowed.has(key)) {
165
- throw new Error(`Invalid system-prompt lock: unknown key ${key}`);
166
- }
167
- }
168
- for (const category of LOCK_CATEGORIES) {
169
- const entries = lock[category];
170
- if (entries === undefined) continue;
171
- if (!entries || typeof entries !== 'object' || Array.isArray(entries)) {
172
- throw new Error(`Invalid system-prompt lock: invalid ${category} selection`);
173
- }
174
- const config = categories[category];
175
- const knownIds = new Set(config.items.map(item => item.id));
176
- for (const [id, entry] of Object.entries(entries)) {
177
- if (!knownIds.has(id)) {
178
- throw new Error(`Invalid system-prompt lock: unknown ${category} item`);
179
- }
180
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
181
- throw new Error(`Invalid system-prompt lock: invalid ${category} entry`);
182
- }
183
- if (typeof entry.source !== 'string' || typeof entry.sourceType !== 'string' || typeof entry.itemPath !== 'string') {
184
- throw new Error(`Invalid system-prompt lock: invalid ${category} entry source`);
185
- }
186
- if (!/^[a-f0-9]{64}$/.test(entry.computedHash || '')) {
187
- throw new Error(`Invalid system-prompt lock: invalid ${category} entry hash`);
188
- }
189
- if (!entry.files || typeof entry.files !== 'object' || Array.isArray(entry.files)) {
190
- throw new Error(`Invalid system-prompt lock: invalid ${category} entry files`);
191
- }
192
- for (const [path, checksum] of Object.entries(entry.files)) {
193
- if (path.startsWith('/') || path.split('/').includes('..') || !/^[a-f0-9]{64}$/.test(checksum)) {
194
- throw new Error('Invalid system-prompt lock: unsafe managed file entry');
195
- }
196
- }
197
- }
198
- }
199
- const generated = lock.generated;
200
- if (generated !== undefined) {
201
- if (!generated || typeof generated !== 'object' || Array.isArray(generated)) {
202
- throw new Error('Invalid system-prompt lock: generated must be an object');
203
- }
204
- for (const [path, entry] of Object.entries(generated)) {
205
- if (path.startsWith('/') || path.split('/').includes('..') || !/^[a-f0-9]{64}$/.test(entry?.computedHash || '')) {
206
- throw new Error('Invalid system-prompt lock: unsafe generated file entry');
207
- }
208
- }
209
- }
210
- }
211
-
212
- function hash(content) {
213
- return createHash('sha256').update(content).digest('hex');
214
- }
215
-
216
- function isInside(parent, child) {
217
- const relativePath = relative(parent, child);
218
- return relativePath === '' || (!relativePath.startsWith('../') && relativePath !== '..' && !isAbsolute(relativePath));
219
- }
220
-
221
- async function canWrite(destFile, relativePath, oldLock, force) {
222
- if (force) return true;
223
- try {
224
- const existing = await readFile(destFile);
225
- const previousHash = getExpectedHash(oldLock, relativePath);
226
- return Boolean(previousHash && previousHash === hash(existing));
227
- } catch (error) {
228
- if (error.code === 'ENOENT') return true;
229
- throw error;
230
- }
231
- }
232
-
233
- async function writeManagedFile(destFile, content, relativePath, options, owner) {
234
- await assertSafeDestination(options.targetDir, destFile);
235
- if (!options.allowExistingMerge && !(await canWrite(destFile, relativePath, options.oldLock, options.force))) {
236
- console.warn(` ⚠ Preserving existing file: ${relativePath}`);
237
- return false;
238
- }
239
- if (!options.dryRun) await mkdir(dirname(destFile), { recursive: true });
240
- if (!options.dryRun) await writeFile(destFile, content);
241
- options.managedFiles[relativePath] = hash(content);
242
- if (owner) options.fileOwners[relativePath] = owner;
243
- return true;
244
- }
245
-
246
- async function copyDir(src, dest, relativeDir, options, owner) {
247
- if (!options.dryRun) await mkdir(dest, { recursive: true });
248
- const entries = await readdir(src, { withFileTypes: true });
249
-
250
- for (const entry of entries) {
251
- if (entry.name === '.DS_Store') continue;
252
- const srcPath = resolve(src, entry.name);
253
- const destPath = resolve(dest, entry.name);
254
- const relativePath = `${relativeDir}/${entry.name}`;
255
-
256
- if (entry.isDirectory()) {
257
- await copyDir(srcPath, destPath, relativePath, options, owner);
258
- } else if (entry.isFile()) {
259
- const content = await readFile(srcPath);
260
- await writeManagedFile(destPath, content, relativePath, options, owner);
261
- }
262
- }
263
- }
264
-
265
- function sourceMissing(error) {
266
- return error?.code === 'ENOENT';
267
- }
268
-
269
- function assertSafePath(targetDir, path) {
270
- if (!isInside(targetDir, path)) {
271
- throw new Error(`Refusing to access path outside installation directory: ${path}`);
272
- }
273
- }
274
-
275
- async function assertSafeDestination(targetDir, path) {
276
- assertSafePath(targetDir, path);
277
- try {
278
- if ((await lstat(targetDir)).isSymbolicLink()) {
279
- throw new Error(`Refusing to install through symlink target: ${targetDir}`);
280
- }
281
- } catch (error) {
282
- if (error.code !== 'ENOENT') throw error;
283
- }
284
- const relativePath = relative(targetDir, path);
285
- let current = targetDir;
286
- for (const part of relativePath.split('/').filter(Boolean)) {
287
- current = resolve(current, part);
288
- try {
289
- if ((await lstat(current)).isSymbolicLink()) {
290
- throw new Error(`Refusing to access symlink inside installation directory: ${current}`);
291
- }
292
- } catch (error) {
293
- if (error.code === 'ENOENT') break;
294
- throw error;
295
- }
296
- }
297
- }
298
-
299
- async function copySelectedDirs(targetDir, category, selectedIds, options) {
300
- const catConfig = categories[category];
301
- if (!catConfig || !selectedIds?.length) return;
302
-
303
- const destParent = resolve(targetDir, targetSubdir(catConfig.sourceDir));
304
-
305
- for (const id of selectedIds) {
306
- if (await isRemoved(category, id)) continue;
307
-
308
- const source = itemSourcePath(category, id);
309
- const srcPath = resolveSource(source);
310
- const destPath = resolve(destParent, id);
311
- await assertSafeDestination(targetDir, destPath);
312
-
313
- try {
314
- await stat(srcPath);
315
- await copyDir(srcPath, destPath, itemRelativePath(category, id), options, { category, id });
316
- } catch (error) {
317
- if (sourceMissing(error)) {
318
- console.warn(` ⚠ Source not found: ${source}`);
319
- continue;
320
- }
321
- throw error;
322
- }
323
- }
324
- }
325
-
326
- async function copySelectedFiles(targetDir, category, selectedIds, options) {
327
- const catConfig = categories[category];
328
- if (!catConfig || !selectedIds?.length) return;
329
-
330
- const destParent = resolve(targetDir, targetSubdir(catConfig.sourceDir));
331
- if (!options.dryRun) await mkdir(destParent, { recursive: true });
332
-
333
- for (const id of selectedIds) {
334
- if (await isRemoved(category, id)) continue;
335
-
336
- const source = itemSourcePath(category, id);
337
- const relativePath = itemRelativePath(category, id);
338
- const destFile = resolve(targetDir, relativePath);
339
- await assertSafeDestination(targetDir, destFile);
340
- try {
341
- const content = await readFile(resolveSource(source));
342
- await writeManagedFile(destFile, content, relativePath, options, { category, id });
343
- } catch (error) {
344
- if (sourceMissing(error)) {
345
- console.warn(` ⚠ Source not found: ${source}`);
346
- continue;
347
- }
348
- throw error;
349
- }
350
- }
351
- }
352
-
353
- async function deleteSelectedItems(absTarget, category, ids, oldLock, force, dryRun) {
354
- if (!categories[category] || !ids?.length || !isCopyable(category)) return;
355
-
356
- for (const id of ids) {
357
- const relativePath = itemRelativePath(category, id);
358
- const destPath = resolve(absTarget, relativePath);
359
- await assertSafeDestination(absTarget, destPath);
360
- if (!force && oldLock) {
361
- const managedEntries = Object.entries(oldLock?.[category]?.[id]?.files || {});
362
- if (managedEntries.length === 0) {
363
- console.warn(` ⚠ Preserving unmanaged item: ${relativePath}`);
364
- continue;
365
- }
366
- let modified = false;
367
- for (const [path, checksum] of managedEntries) {
368
- await assertSafeDestination(absTarget, resolve(absTarget, path));
369
- try {
370
- if (hash(await readFile(resolve(absTarget, path))) !== checksum) modified = true;
371
- } catch (error) {
372
- if (!sourceMissing(error)) throw error;
373
- }
374
- }
375
- if (modified) {
376
- console.warn(` ⚠ Preserving modified item: ${relativePath}`);
377
- continue;
378
- }
379
- if (!isFileBased(category)) {
380
- if (!dryRun) {
381
- for (const [path] of managedEntries) await rm(resolve(absTarget, path), { force: true });
382
- }
383
- continue;
384
- }
385
- }
386
- if (!dryRun) await rm(destPath, { recursive: true, force: true });
387
- }
388
- }
389
-
390
- async function mergeJsonFile(destFile, generated, relativePath, options, previousGenerated = generated) {
391
- let existing = {};
392
- try {
393
- existing = JSON.parse(await readFile(destFile, 'utf-8'));
394
- } catch (error) {
395
- if (error.code !== 'ENOENT') {
396
- if (error instanceof SyntaxError) throw new Error(`Cannot merge invalid JSON file: ${relativePath}`);
397
- throw error;
398
- }
399
- }
400
- const merged = { ...existing, ...generated };
401
- if (Array.isArray(existing.instructions) && Array.isArray(generated.instructions)) {
402
- const previous = new Set(previousGenerated.instructions || []);
403
- merged.instructions = [...new Set([
404
- ...existing.instructions.filter(item => !previous.has(item)),
405
- ...generated.instructions,
406
- ])];
407
- }
408
- if (Array.isArray(existing.plugin)) {
409
- const previous = new Set(previousGenerated.plugin || []);
410
- const plugins = [...new Set([
411
- ...existing.plugin.filter(item => !previous.has(item)),
412
- ...(generated.plugin || []),
413
- ])];
414
- if (plugins.length) merged.plugin = plugins;
415
- else delete merged.plugin;
416
- }
417
- for (const key of ['mcp', 'references']) {
418
- if (existing[key] && typeof existing[key] === 'object') {
419
- const previous = previousGenerated[key] || {};
420
- const preserved = Object.fromEntries(Object.entries(existing[key]).filter(([name]) => !(name in previous)));
421
- const values = { ...preserved, ...(generated[key] || {}) };
422
- if (Object.keys(values).length) merged[key] = values;
423
- else delete merged[key];
424
- }
425
- }
426
- return writeManagedFile(destFile, Buffer.from(JSON.stringify(merged, null, 4)), relativePath, {
427
- ...options,
428
- allowExistingMerge: !options.oldLock,
429
- }, { generated: true });
430
- }
431
-
432
- async function mergeGitignore(destFile, options) {
433
- let existing = '';
434
- try {
435
- existing = await readFile(destFile, 'utf-8');
436
- } catch (error) {
437
- if (error.code !== 'ENOENT') throw error;
438
- }
439
- const lines = new Set(existing.split('\n').filter(Boolean));
440
- for (const line of OPENCODE_GITIGNORE.split('\n').filter(Boolean)) lines.add(line);
441
- return writeManagedFile(destFile, Buffer.from(`${[...lines].join('\n')}\n`), '.gitignore', {
442
- ...options,
443
- allowExistingMerge: !options.oldLock,
444
- }, { generated: true });
445
- }
446
-
447
- export function validateSelections(selections) {
448
- if (!selections || typeof selections !== 'object' || Array.isArray(selections)) {
449
- throw new Error('Selections must be an object');
450
- }
451
- for (const [category, ids] of Object.entries(selections)) {
452
- const config = categories[category];
453
- if (!config || !Array.isArray(ids)) throw new Error(`Unknown or invalid category: ${category}`);
454
- const knownIds = new Set(config.items.map(item => item.id));
455
- if (ids.some(id => !knownIds.has(id))) throw new Error(`Unknown ${category} item selected`);
456
- }
457
- return selections;
458
- }
459
-
460
- export async function install({ targetDir, agentType, selections, includeAgentsMd = true, writeAgentsMd, oldSelections, oldLock, force = false, dryRun = false, tuiPreferences }) {
461
- validateSelections(selections);
462
- if (oldLock) validateLock(oldLock);
463
- writeAgentsMd = writeAgentsMd ?? includeAgentsMd;
464
- const absTarget = resolve(process.cwd(), targetDir);
465
- if (!dryRun) await mkdir(absTarget, { recursive: true });
466
- const options = {
467
- targetDir: absTarget,
468
- oldLock,
469
- force,
470
- dryRun,
471
- managedFiles: {},
472
- fileOwners: {},
473
- };
474
- if (oldLock) {
475
- for (const category of LOCK_CATEGORIES) {
476
- for (const [id, entry] of Object.entries(oldLock[category] || {})) {
477
- for (const [path, checksum] of Object.entries(entry.files || {})) {
478
- if (!(path in options.managedFiles)) {
479
- options.managedFiles[path] = checksum;
480
- options.fileOwners[path] = { category, id };
481
- }
482
- }
483
- }
484
- }
485
- for (const [path, entry] of Object.entries(oldLock.generated || {})) {
486
- if (!(path in options.managedFiles)) {
487
- options.managedFiles[path] = entry.computedHash;
488
- options.fileOwners[path] = { generated: true };
489
- }
490
- }
491
- }
492
-
493
- // Delete items that are no longer selected.
494
- if (oldSelections) {
495
- for (const cat of Object.keys(oldSelections)) {
496
- const oldIds = new Set(oldSelections[cat] || []);
497
- const newIds = new Set(selections[cat] || []);
498
- const removedIds = [...oldIds].filter(id => !newIds.has(id));
499
- await deleteSelectedItems(absTarget, cat, removedIds, oldLock, force, dryRun);
500
- }
501
- }
502
-
503
- const tasks = [];
504
- for (const category of LOCK_CATEGORIES) {
505
- if (!isCopyable(category) || !selections[category]?.length) continue;
506
- tasks.push(isFileBased(category)
507
- ? copySelectedFiles(absTarget, category, selections[category], options)
508
- : copySelectedDirs(absTarget, category, selections[category], options));
509
- }
510
- await Promise.all(tasks);
511
-
512
- if (writeAgentsMd) {
513
- await writeManagedFile(resolve(absTarget, 'AGENTS.md'), Buffer.from(AGENTS_MD), 'AGENTS.md', options, { generated: true });
514
- }
515
-
516
- if (agentType === 'opencode') {
517
- let mcpEntries = {};
518
- if (selections.mcps?.length) mcpEntries = await loadMcpConfigs(selections.mcps);
519
- let previousOpenCodeConfig;
520
- let previousTuiConfig;
521
- if (oldLock) {
522
- const oldSelections = lockToSelections(oldLock);
523
- let previousMcpEntries = {};
524
- if (oldSelections.mcps?.length) previousMcpEntries = await loadMcpConfigs(oldSelections.mcps);
525
- previousOpenCodeConfig = JSON.parse(generateOpenCodeConfig({
526
- selections: oldSelections,
527
- mcpEntries: previousMcpEntries,
528
- includeAgentsMd: oldLock.includeAgentsMd ?? true,
529
- }));
530
- previousTuiConfig = JSON.parse(generateTuiConfig({ selections: oldSelections, preferences: tuiPreferences }));
531
- }
532
- const configJson = generateOpenCodeConfig({ selections, mcpEntries, includeAgentsMd });
533
- await mergeJsonFile(resolve(absTarget, 'opencode.json'), JSON.parse(configJson), 'opencode.json', options, previousOpenCodeConfig);
534
- await mergeJsonFile(resolve(absTarget, 'tui.json'), JSON.parse(generateTuiConfig({ selections, preferences: tuiPreferences })), 'tui.json', options, previousTuiConfig);
535
- await mergeGitignore(resolve(absTarget, '.gitignore'), options);
536
- }
537
-
538
- if (selections.mcps?.length) {
539
- const envExamples = await collectMcpEnvExamples(selections.mcps);
540
- await writeMergedEnv(absTarget, envExamples, options);
541
- }
542
-
543
- if (dryRun) return absTarget;
544
- const pkgVersion = await getPackageVersion();
545
- const source = `system-prompt@${pkgVersion}`;
546
- const lockData = {
547
- version: LOCK_VERSION,
548
- agentType,
549
- installedAt: new Date().toISOString(),
550
- includeAgentsMd,
551
- };
552
- for (const category of LOCK_CATEGORIES) {
553
- const entries = {};
554
- for (const id of selections[category] || []) {
555
- if (await isRemoved(category, id)) continue;
556
- const files = {};
557
- for (const [path, checksum] of Object.entries(options.managedFiles)) {
558
- const owner = options.fileOwners[path];
559
- if (owner?.category === category && owner?.id === id) files[path] = checksum;
560
- }
561
- entries[id] = {
562
- source,
563
- sourceType: 'bundled',
564
- itemPath: itemSourcePath(category, id),
565
- computedHash: buildComputedHash(files, id),
566
- files,
567
- };
568
- }
569
- lockData[category] = entries;
570
- }
571
- const generated = {};
572
- for (const [path, checksum] of Object.entries(options.managedFiles)) {
573
- if (options.fileOwners[path]?.generated) generated[path] = { computedHash: checksum };
574
- }
575
- lockData.generated = generated;
576
- await writeFile(resolve(absTarget, 'system-prompt-lock.json'), JSON.stringify(lockData, null, 2));
577
- return absTarget;
578
- }
579
-
580
- function resolveSource(subpath) {
581
- return resolve(packageRoot, subpath);
582
- }
583
-
584
- async function isRemoved(category, id) {
585
- const catConfig = categories[category];
586
- if (!catConfig) return false;
587
- const item = catConfig.items.find(i => i.id === id);
588
- return item?.removed === true;
589
- }
590
-
591
- function parseEnv(content) {
592
- const vars = new Map();
593
- for (const line of content.split('\n')) {
594
- const trimmed = line.trim();
595
- if (!trimmed || trimmed.startsWith('#')) continue;
596
- const eqIndex = trimmed.indexOf('=');
597
- if (eqIndex === -1) {
598
- vars.set(trimmed, '');
599
- } else {
600
- const key = trimmed.slice(0, eqIndex).trim();
601
- const value = trimmed.slice(eqIndex + 1).trim();
602
- if (key) vars.set(key, value);
603
- }
604
- }
605
- return vars;
606
- }
607
-
608
- async function collectMcpEnvExamples(mcpIds) {
609
- const combined = new Map();
610
- for (const id of mcpIds) {
611
- try {
612
- const examplePath = resolveSource(`framework/mcps/${id}/configs/.env.example`);
613
- const content = await readFile(examplePath, 'utf-8');
614
- const parsed = parseEnv(content);
615
- for (const [key, value] of parsed) {
616
- if (!combined.has(key)) combined.set(key, value);
617
- }
618
- } catch (error) {
619
- if (error.code !== 'ENOENT') throw error;
620
- // MCPs may not provide an environment example.
621
- }
622
- }
623
- return combined;
624
- }
625
-
626
- async function writeMergedEnv(absTarget, examples, options) {
627
- if (examples.size === 0) return;
628
-
629
- const envPath = resolve(absTarget, '.env');
630
- await assertSafeDestination(options.targetDir, envPath);
631
- const existing = new Map();
632
- let existingContent = '';
633
-
634
- try {
635
- existingContent = await readFile(envPath, 'utf-8');
636
- const parsed = parseEnv(existingContent);
637
- for (const [key, value] of parsed) existing.set(key, value);
638
- } catch (error) {
639
- if (error.code !== 'ENOENT') throw error;
640
- }
641
-
642
- const additions = [];
643
- for (const [key, value] of examples) {
644
- if (!existing.has(key)) additions.push(`${key}=${value}`);
645
- }
646
-
647
- if (additions.length === 0) return;
648
- const separator = existingContent && !existingContent.endsWith('\n') ? '\n' : '';
649
- const content = Buffer.from(`${existingContent}${separator}${additions.join('\n')}\n`);
650
- if (!options.dryRun) await writeFile(envPath, content);
651
- options.managedFiles['.env'] = hash(content);
652
- options.fileOwners['.env'] = { generated: true };
653
- }