obsidian-plugin-config 1.5.8 → 1.5.10

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.
@@ -1,736 +1,738 @@
1
- #!/usr/bin/env tsx
2
-
3
- import fs from 'fs';
4
- import path from 'path';
5
- import { execSync } from 'child_process';
6
- import { fileURLToPath } from 'url';
7
- import { isValidPath, gitExec } from './utils.js';
8
-
9
- export interface InjectionPlan {
10
- targetPath: string;
11
- isObsidianPlugin: boolean;
12
- hasPackageJson: boolean;
13
- hasManifest: boolean;
14
- hasScriptsFolder: boolean;
15
- currentDependencies: string[];
16
- }
17
-
18
- /**
19
- * Analyze the target plugin directory
20
- */
21
- export async function analyzePlugin(pluginPath: string): Promise<InjectionPlan> {
22
- const packageJsonPath = path.join(pluginPath, 'package.json');
23
- const manifestPath = path.join(pluginPath, 'manifest.json');
24
- const scriptsPath = path.join(pluginPath, 'scripts');
25
-
26
- const plan: InjectionPlan = {
27
- targetPath: pluginPath,
28
- isObsidianPlugin: false,
29
- hasPackageJson: await isValidPath(packageJsonPath),
30
- hasManifest: await isValidPath(manifestPath),
31
- hasScriptsFolder: await isValidPath(scriptsPath),
32
- currentDependencies: []
33
- };
34
-
35
- if (plan.hasManifest) {
36
- try {
37
- const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
38
- plan.isObsidianPlugin = !!(manifest.id && manifest.name && manifest.version);
39
- } catch {
40
- console.warn('Warning: Could not parse manifest.json');
41
- }
42
- }
43
-
44
- if (plan.hasPackageJson) {
45
- try {
46
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
47
- plan.currentDependencies = [
48
- ...Object.keys(packageJson.dependencies || {}),
49
- ...Object.keys(packageJson.devDependencies || {})
50
- ];
51
- } catch {
52
- console.warn('Warning: Could not parse package.json');
53
- }
54
- }
55
-
56
- return plan;
57
- }
58
-
59
- /**
60
- * Find plugin-config root directory (handles NPM global installs)
61
- */
62
- export function findPluginConfigRoot(): string {
63
- const scriptDir = path.dirname(fileURLToPath(import.meta.url));
64
- const npmPackageRoot = path.resolve(scriptDir, '..');
65
- const npmPackageJson = path.join(npmPackageRoot, 'package.json');
66
-
67
- if (fs.existsSync(npmPackageJson)) {
68
- try {
69
- const packageContent = JSON.parse(fs.readFileSync(npmPackageJson, 'utf8'));
70
- if (packageContent.name === 'obsidian-plugin-config') {
71
- return npmPackageRoot;
72
- }
73
- } catch {
74
- // Ignore parsing errors
75
- }
76
- }
77
-
78
- return process.cwd();
79
- }
80
-
81
- /**
82
- * Copy file content from local plugin-config directory
83
- */
84
- export function copyFromLocal(filePath: string): string {
85
- const configRoot = findPluginConfigRoot();
86
- const sourcePath = path.join(configRoot, filePath);
87
-
88
- try {
89
- return fs.readFileSync(sourcePath, 'utf8');
90
- } catch (error) {
91
- throw new Error(`Failed to copy ${filePath}: ${error}`);
92
- }
93
- }
94
-
95
- /**
96
- * Check if plugin-config repo is clean and commit if needed
97
- */
98
- export async function ensurePluginConfigClean(): Promise<void> {
99
- const configRoot = findPluginConfigRoot();
100
- const gitDir = path.join(configRoot, '.git');
101
-
102
- // Skip git check if not a git repo
103
- // (e.g. NPM global install)
104
- if (!fs.existsSync(gitDir)) {
105
- console.log(`✅ Plugin-config repo is clean` + ` (NPM install, no git check)`);
106
- return;
107
- }
108
-
109
- const originalCwd = process.cwd();
110
-
111
- try {
112
- process.chdir(configRoot);
113
- const gitStatus = execSync('git status --porcelain', { encoding: 'utf8' }).trim();
114
-
115
- if (gitStatus) {
116
- console.log(`\n⚠️ Plugin-config has uncommitted changes:`);
117
- console.log(gitStatus);
118
- console.log(`\n🔧 Auto-committing changes...`);
119
-
120
- const msg = '🔧 Update plugin-config templates';
121
- gitExec('git add -A');
122
- gitExec(`git commit -m "${msg}"`);
123
-
124
- try {
125
- const branch = execSync('git rev-parse --abbrev-ref HEAD', {
126
- encoding: 'utf8'
127
- }).trim();
128
- gitExec(`git push origin ${branch}`);
129
- console.log(`✅ Changes committed and pushed`);
130
- } catch {
131
- try {
132
- const branch = execSync('git rev-parse --abbrev-ref HEAD', {
133
- encoding: 'utf8'
134
- }).trim();
135
- gitExec(`git push --set-upstream origin ${branch}`);
136
- console.log(`✅ New branch pushed with upstream`);
137
- } catch {
138
- console.log(`⚠️ Committed locally, push failed`);
139
- }
140
- }
141
- } else {
142
- console.log(`✅ Plugin-config repo is clean`);
143
- }
144
- } finally {
145
- process.chdir(originalCwd);
146
- }
147
- }
148
-
149
- /**
150
- * Display injection plan and ask for confirmation
151
- */
152
- export async function showInjectionPlan(
153
- plan: InjectionPlan,
154
- autoConfirm: boolean = false,
155
- useSass: boolean = false
156
- ): Promise<boolean> {
157
- const { askConfirmation, createReadlineInterface } = await import('./utils.js');
158
- const rl = createReadlineInterface();
159
-
160
- console.log(`\n🎯 Injection Plan for: ${plan.targetPath}`);
161
- console.log(`📁 Target: ${path.basename(plan.targetPath)}`);
162
- console.log(`📦 Package.json: ${plan.hasPackageJson ? '✅' : '❌'}`);
163
- console.log(`📋 Manifest.json: ${plan.hasManifest ? '✅' : '❌'}`);
164
- console.log(
165
- `📂 Scripts folder: ${plan.hasScriptsFolder ? '✅ (will be updated)' : '❌ (will be created)'}`
166
- );
167
- console.log(`🔌 Obsidian plugin: ${plan.isObsidianPlugin ? '✅' : '❌'}`);
168
- console.log(
169
- `🎨 SASS support: ${useSass ? '✅ (esbuild-sass-plugin will be added)' : '❌'}`
170
- );
171
-
172
- if (!plan.isObsidianPlugin) {
173
- console.log(`\n⚠️ Warning: This doesn't appear to be a valid Obsidian plugin`);
174
- console.log(` Missing manifest.json or invalid structure`);
175
- }
176
-
177
- console.log(`\n📋 Will inject:`);
178
- console.log(` ✅ Local scripts (utils.ts, esbuild.config.ts, acp.ts, etc.)`);
179
- console.log(` ✅ Updated package.json scripts`);
180
- console.log(` ✅ Required dependencies`);
181
- console.log(` 🔍 Analyze centralized imports (manual commenting may be needed)`);
182
-
183
- if (autoConfirm) {
184
- console.log(`\n✅ Auto-confirming injection...`);
185
- rl.close();
186
- return true;
187
- }
188
-
189
- const result = await askConfirmation(`\nProceed with injection?`, rl);
190
- rl.close();
191
- return result;
192
- }
193
-
194
- /**
195
- * Clean old script files
196
- */
197
- export async function cleanOldScripts(scriptsPath: string): Promise<void> {
198
- const scriptNames = [
199
- 'utils',
200
- 'esbuild.config',
201
- 'acp',
202
- 'update-version',
203
- 'release',
204
- 'help'
205
- ];
206
- const extensions = ['.ts', '.mts', '.js', '.mjs'];
207
-
208
- for (const scriptName of scriptNames) {
209
- for (const ext of extensions) {
210
- const scriptFile = path.join(scriptsPath, `${scriptName}${ext}`);
211
- if (await isValidPath(scriptFile)) {
212
- fs.unlinkSync(scriptFile);
213
- console.log(
214
- `🗑️ Removed existing ${scriptName}${ext} (will be replaced)`
215
- );
216
- }
217
- }
218
- }
219
-
220
- const obsoleteRootFiles = ['help-plugin.ts'];
221
- for (const fileName of obsoleteRootFiles) {
222
- const filePath = path.join(path.dirname(scriptsPath), fileName);
223
- if (await isValidPath(filePath)) {
224
- fs.unlinkSync(filePath);
225
- console.log(`🗑️ Removed obsolete root file: ${fileName}`);
226
- }
227
- }
228
-
229
- const obsoleteFiles = ['start.mjs', 'start.js'];
230
- for (const fileName of obsoleteFiles) {
231
- const filePath = path.join(scriptsPath, fileName);
232
- if (await isValidPath(filePath)) {
233
- fs.unlinkSync(filePath);
234
- console.log(`🗑️ Removed obsolete file: ${fileName}`);
235
- }
236
- }
237
- }
238
-
239
- /**
240
- * Clean old ESLint config files
241
- */
242
- export async function cleanOldLintFiles(targetPath: string): Promise<void> {
243
- const oldLintFiles = ['.eslintrc', '.eslintrc.js', '.eslintrc.json', '.eslintignore'];
244
- const conflictingLintFiles = [
245
- 'eslint.config.ts',
246
- 'eslint.config.cjs',
247
- 'eslint.config.js',
248
- 'eslint.config.mjs'
249
- ];
250
-
251
- for (const fileName of oldLintFiles) {
252
- const filePath = path.join(targetPath, fileName);
253
- if (await isValidPath(filePath)) {
254
- fs.unlinkSync(filePath);
255
- console.log(
256
- `🗑️ Removed old ESLint file: ${fileName} (replaced by eslint.config.ts)`
257
- );
258
- }
259
- }
260
-
261
- for (const fileName of conflictingLintFiles) {
262
- const filePath = path.join(targetPath, fileName);
263
- if (await isValidPath(filePath)) {
264
- fs.unlinkSync(filePath);
265
- console.log(
266
- `🗑️ Removed existing ESLint file: ${fileName} (will be replaced by injection)`
267
- );
268
- }
269
- }
270
- }
271
-
272
- /**
273
- * Inject scripts and config files
274
- */
275
- export async function injectScripts(targetPath: string): Promise<void> {
276
- const scriptsPath = path.join(targetPath, 'scripts');
277
-
278
- if (!(await isValidPath(scriptsPath))) {
279
- fs.mkdirSync(scriptsPath, { recursive: true });
280
- console.log(`📁 Created scripts directory`);
281
- }
282
-
283
- await cleanOldScripts(scriptsPath);
284
- await cleanOldLintFiles(targetPath);
285
-
286
- const scriptFiles = [
287
- 'templates/scripts/utils.ts',
288
- 'templates/scripts/esbuild.config.ts',
289
- 'templates/scripts/acp.ts',
290
- 'templates/scripts/update-version.ts',
291
- 'templates/scripts/release.ts',
292
- 'templates/scripts/help.ts'
293
- ];
294
-
295
- // Files that need value-preserving merge instead
296
- // of full overwrite (user fills in their paths)
297
- const mergeEnvFile = new Set(['.env']);
298
-
299
- // Files with .template suffix (NPM excludes dotfiles)
300
- // Map: { source: targetName }
301
- const configFileMap: Record<string, string> = {
302
- 'templates/tsconfig.json': 'tsconfig.json',
303
- 'templates/gitignore.template': '.gitignore',
304
- 'templates/eslint.config.mts': 'eslint.config.mts',
305
- 'templates/.editorconfig': '.editorconfig',
306
- 'templates/.prettierrc': '.prettierrc',
307
- 'templates/npmrc.template': '.npmrc',
308
- 'templates/env.template': '.env'
309
- };
310
-
311
- const configVscodeMap: Record<string, string> = {
312
- 'templates/.vscode/settings.json': '.vscode/settings.json',
313
- 'templates/.vscode/tasks.json': '.vscode/tasks.json'
314
- };
315
-
316
- const workflowFiles = [
317
- 'templates/.github/workflows/release.yml',
318
- 'templates/.github/workflows/release-body.md'
319
- ];
320
-
321
- console.log(`\n📥 Copying scripts from local files...`);
322
-
323
- for (const scriptFile of scriptFiles) {
324
- try {
325
- const content = copyFromLocal(scriptFile);
326
- const fileName = path.basename(scriptFile);
327
- const targetFile = path.join(scriptsPath, fileName);
328
- fs.writeFileSync(targetFile, content, 'utf8');
329
- console.log(` ✅ ${fileName}`);
330
- } catch (error) {
331
- console.error(` ❌ Failed to inject ${scriptFile}: ${error}`);
332
- }
333
- }
334
-
335
- console.log(`\n📥 Copying config files...`);
336
-
337
- // Copy root config files
338
- for (const [src, destName] of Object.entries(configFileMap)) {
339
- try {
340
- const targetFile = path.join(targetPath, destName);
341
- const templateContent = copyFromLocal(src);
342
-
343
- // For .env: merge existing values into the template
344
- if (mergeEnvFile.has(destName) && fs.existsSync(targetFile)) {
345
- const existing = fs.readFileSync(targetFile, 'utf8');
346
- // Parse existing key=value pairs
347
- const existingVals: Record<string, string> = {};
348
- for (const line of existing.split(/\r?\n/)) {
349
- const m = line.match(/^([^#=]+)=(.*)$/);
350
- if (m) existingVals[m[1].trim()] = m[2].trim();
351
- }
352
- // Re-write template, substituting existing values
353
- const merged = templateContent
354
- .split(/\r?\n/)
355
- .map((line) => {
356
- const m = line.match(/^([^#=]+)=(.*)$/);
357
- if (m) {
358
- const key = m[1].trim();
359
- const val = existingVals[key] ?? m[2].trim();
360
- return `${key}=${val}`;
361
- }
362
- return line;
363
- })
364
- .join('\n');
365
- fs.writeFileSync(targetFile, merged, 'utf8');
366
- console.log(` ✅ ${destName} (values preserved)`);
367
- continue;
368
- }
369
-
370
- fs.writeFileSync(targetFile, templateContent, 'utf8');
371
- console.log(` ✅ ${destName}`);
372
- } catch (error) {
373
- console.error(` ❌ Failed to inject ${destName}: ${error}`);
374
- }
375
- }
376
-
377
- // Copy .vscode config files
378
- for (const [src, destName] of Object.entries(configVscodeMap)) {
379
- try {
380
- const content = copyFromLocal(src);
381
- const targetFile = path.join(targetPath, destName);
382
- const targetDir = path.dirname(targetFile);
383
- if (!(await isValidPath(targetDir))) {
384
- fs.mkdirSync(targetDir, { recursive: true });
385
- }
386
- fs.writeFileSync(targetFile, content, 'utf8');
387
- console.log(` ✅ ${destName}`);
388
- } catch (error) {
389
- console.error(` ❌ Failed to inject ${destName}: ${error}`);
390
- }
391
- }
392
-
393
- console.log(`\n📥 Copying GitHub workflows from local files...`);
394
-
395
- for (const workflowFile of workflowFiles) {
396
- try {
397
- const content = copyFromLocal(workflowFile);
398
- const relativePath = workflowFile.replace('templates/', '');
399
- const targetFile = path.join(targetPath, relativePath);
400
- const targetDir = path.dirname(targetFile);
401
-
402
- if (!(await isValidPath(targetDir))) {
403
- fs.mkdirSync(targetDir, { recursive: true });
404
- }
405
-
406
- fs.writeFileSync(targetFile, content, 'utf8');
407
- console.log(` ✅ ${relativePath}`);
408
- } catch (error) {
409
- console.error(` ❌ Failed to inject ${workflowFile}: ${error}`);
410
- }
411
- }
412
- }
413
-
414
- /**
415
- * Update package.json with autonomous configuration
416
- */
417
- export async function updatePackageJson(
418
- targetPath: string,
419
- useSass: boolean = false
420
- ): Promise<void> {
421
- const packageJsonPath = path.join(targetPath, 'package.json');
422
-
423
- if (!(await isValidPath(packageJsonPath))) {
424
- console.log(`❌ No package.json found, skipping package.json update`);
425
- return;
426
- }
427
-
428
- try {
429
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
430
-
431
- const configRoot = findPluginConfigRoot();
432
- const templatePkg = JSON.parse(
433
- fs.readFileSync(path.join(configRoot, 'templates/package.json'), 'utf8')
434
- );
435
-
436
- if (useSass) {
437
- const sassPkg = JSON.parse(
438
- fs.readFileSync(
439
- path.join(configRoot, 'templates/package-sass.json'),
440
- 'utf8'
441
- )
442
- );
443
- Object.assign(templatePkg.devDependencies, sassPkg.devDependencies);
444
- }
445
-
446
- const obsoleteScripts = ['version'];
447
- for (const script of obsoleteScripts) {
448
- if (packageJson.scripts?.[script]) {
449
- console.log(` 🧹 Removing obsolete script: "${script}"`);
450
- delete packageJson.scripts[script];
451
- }
452
- }
453
-
454
- packageJson.scripts = {
455
- ...packageJson.scripts,
456
- ...templatePkg.scripts
457
- };
458
-
459
- if (!packageJson.devDependencies) packageJson.devDependencies = {};
460
-
461
- const requiredDeps: Record<string, string> = templatePkg.devDependencies;
462
-
463
- let addedDeps = 0;
464
- let updatedDeps = 0;
465
- for (const [dep, version] of Object.entries(requiredDeps)) {
466
- if (!packageJson.devDependencies[dep]) {
467
- packageJson.devDependencies[dep] = version as string;
468
- addedDeps++;
469
- } else if (packageJson.devDependencies[dep] !== version) {
470
- packageJson.devDependencies[dep] = version as string;
471
- updatedDeps++;
472
- }
473
- }
474
-
475
- if (!packageJson.engines) packageJson.engines = {};
476
- packageJson.engines.npm = templatePkg.engines.npm;
477
- packageJson.engines.yarn = templatePkg.engines.yarn;
478
- packageJson.type = templatePkg.type;
479
-
480
- fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
481
- console.log(
482
- ` ✅ Updated package.json (${addedDeps} new, ${updatedDeps} updated dependencies)`
483
- );
484
- } catch (error) {
485
- console.error(` ❌ Failed to update package.json: ${error}`);
486
- }
487
- }
488
-
489
- /**
490
- * Analyze centralized imports in source files (without modifying)
491
- */
492
- export async function analyzeCentralizedImports(targetPath: string): Promise<void> {
493
- const srcPath = path.join(targetPath, 'src');
494
-
495
- if (!(await isValidPath(srcPath))) {
496
- console.log(` ℹ️ No src directory found`);
497
- return;
498
- }
499
-
500
- console.log(`\n🔍 Analyzing centralized imports...`);
501
-
502
- try {
503
- const findTsFiles = (dir: string): string[] => {
504
- const files: string[] = [];
505
- for (const item of fs.readdirSync(dir)) {
506
- const fullPath = path.join(dir, item);
507
- if (fs.statSync(fullPath).isDirectory()) {
508
- files.push(...findTsFiles(fullPath));
509
- } else if (item.endsWith('.ts') || item.endsWith('.tsx')) {
510
- files.push(fullPath);
511
- }
512
- }
513
- return files;
514
- };
515
-
516
- const tsFiles = findTsFiles(srcPath);
517
- let filesWithImports = 0;
518
-
519
- for (const filePath of tsFiles) {
520
- try {
521
- const content = fs.readFileSync(filePath, 'utf8');
522
- const importRegex =
523
- /import\s+.*from\s+["']obsidian-plugin-config[^"']*["']/g;
524
- if (importRegex.test(content)) {
525
- filesWithImports++;
526
- console.log(
527
- ` ⚠️ ${path.relative(targetPath, filePath)} - contains centralized imports`
528
- );
529
- }
530
- } catch (error) {
531
- console.warn(
532
- ` ⚠️ Could not analyze ${path.relative(targetPath, filePath)}: ${error}`
533
- );
534
- }
535
- }
536
-
537
- if (filesWithImports === 0) {
538
- console.log(` ✅ No centralized imports found`);
539
- } else {
540
- console.log(
541
- ` ⚠️ Found ${filesWithImports} files with centralized imports`
542
- );
543
- console.log(
544
- ` 💡 You may need to manually comment these imports for the plugin to work`
545
- );
546
- }
547
- } catch (error) {
548
- console.error(` ❌ Failed to analyze imports: ${error}`);
549
- }
550
- }
551
-
552
- /**
553
- * Create required directories
554
- */
555
- export async function createRequiredDirectories(targetPath: string): Promise<void> {
556
- const directories = [path.join(targetPath, '.github', 'workflows')];
557
-
558
- for (const dir of directories) {
559
- if (!(await isValidPath(dir))) {
560
- fs.mkdirSync(dir, { recursive: true });
561
- console.log(` 📁 Created ${path.relative(targetPath, dir)}`);
562
- }
563
- }
564
- }
565
-
566
- /**
567
- * Create injection info file
568
- */
569
- export async function createInjectionInfo(targetPath: string): Promise<void> {
570
- const configRoot = findPluginConfigRoot();
571
- const configPackageJsonPath = path.join(configRoot, 'package.json');
572
-
573
- let injectorVersion = 'unknown';
574
- try {
575
- const configPackageJson = JSON.parse(
576
- fs.readFileSync(configPackageJsonPath, 'utf8')
577
- );
578
- injectorVersion = configPackageJson.version || 'unknown';
579
- } catch {
580
- console.warn('Warning: Could not read injector version');
581
- }
582
-
583
- const injectionInfo = {
584
- injectorVersion,
585
- injectionDate: new Date().toISOString(),
586
- injectorName: 'obsidian-plugin-config'
587
- };
588
-
589
- const infoPath = path.join(targetPath, '.injection-info.json');
590
- fs.writeFileSync(infoPath, JSON.stringify(injectionInfo, null, 2));
591
- console.log(` ✅ Created injection info file (.injection-info.json)`);
592
- }
593
-
594
- /**
595
- * Read injection info from target plugin
596
- */
597
- export function readInjectionInfo(targetPath: string): Record<string, string> | null {
598
- const infoPath = path.join(targetPath, '.injection-info.json');
599
-
600
- if (!fs.existsSync(infoPath)) return null;
601
-
602
- try {
603
- return JSON.parse(fs.readFileSync(infoPath, 'utf8'));
604
- } catch {
605
- console.warn('Warning: Could not parse .injection-info.json');
606
- return null;
607
- }
608
- }
609
-
610
- /**
611
- * Clean NPM/Yarn lock files and node_modules to ensure fresh install
612
- */
613
- export async function cleanNpmArtifactsIfNeeded(targetPath: string): Promise<void> {
614
- const packageLockPath = path.join(targetPath, 'package-lock.json');
615
- const yarnLockPath = path.join(targetPath, 'yarn.lock');
616
- const nodeModulesPath = path.join(targetPath, 'node_modules');
617
-
618
- const hasPackageLock = fs.existsSync(packageLockPath);
619
- const hasYarnLock = fs.existsSync(yarnLockPath);
620
-
621
- if (hasPackageLock || hasYarnLock) {
622
- console.log(`\n🧹 Cleaning lock files and node_modules...`);
623
-
624
- try {
625
- if (hasPackageLock) {
626
- fs.unlinkSync(packageLockPath);
627
- console.log(` 🗑️ Removed package-lock.json`);
628
- }
629
-
630
- if (hasYarnLock) {
631
- fs.unlinkSync(yarnLockPath);
632
- console.log(` 🗑️ Removed yarn.lock`);
633
- }
634
-
635
- if (fs.existsSync(nodeModulesPath)) {
636
- fs.rmSync(nodeModulesPath, { recursive: true, force: true });
637
- console.log(
638
- ` 🗑️ Removed node_modules (will be reinstalled with Yarn)`
639
- );
640
- }
641
-
642
- console.log(` ✅ Lock files and artifacts cleaned for fresh install`);
643
- } catch (error) {
644
- console.error(` Failed to clean artifacts: ${error}`);
645
- console.log(
646
- ` 💡 You may need to manually remove package-lock.json, yarn.lock and node_modules`
647
- );
648
- }
649
- }
650
- }
651
-
652
- /**
653
- * Check if tsx is installed locally and install it if needed
654
- */
655
- export async function ensureTsxInstalled(targetPath: string): Promise<void> {
656
- console.log(`\n🔍 Checking tsx installation...`);
657
-
658
- const packageJsonPath = path.join(targetPath, 'package.json');
659
-
660
- try {
661
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
662
- const devDependencies = packageJson.devDependencies || {};
663
- const dependencies = packageJson.dependencies || {};
664
-
665
- if (devDependencies.tsx || dependencies.tsx) {
666
- console.log(` ✅ tsx is already installed`);
667
- return;
668
- }
669
-
670
- console.log(` ⚠️ tsx not found, installing as dev dependency...`);
671
- execSync('yarn add -D tsx', { cwd: targetPath, stdio: 'inherit' });
672
- console.log(` tsx installed successfully`);
673
- } catch (error) {
674
- console.error(` Failed to install tsx: ${error}`);
675
- console.log(` 💡 You may need to install tsx manually: yarn add -D tsx`);
676
- throw new Error('tsx installation failed');
677
- }
678
- }
679
-
680
- /**
681
- * Run yarn install in target directory
682
- */
683
- export async function runYarnInstall(targetPath: string): Promise<void> {
684
- console.log(`\n📦 Installing dependencies...`);
685
-
686
- try {
687
- execSync('yarn install', { cwd: targetPath, stdio: 'inherit' });
688
- console.log(` ✅ Dependencies installed successfully`);
689
- } catch (error) {
690
- console.error(` Failed to install dependencies: ${error}`);
691
- console.log(
692
- ` 💡 You may need to run 'yarn install' manually in the target directory`
693
- );
694
- }
695
- }
696
-
697
- /**
698
- * Main injection orchestration function
699
- */
700
- export async function performInjection(
701
- targetPath: string,
702
- useSass: boolean = false
703
- ): Promise<void> {
704
- console.log(`\n🚀 Starting injection process...`);
705
-
706
- try {
707
- await cleanNpmArtifactsIfNeeded(targetPath);
708
- await ensureTsxInstalled(targetPath);
709
- await injectScripts(targetPath);
710
-
711
- console.log(`\n📦 Updating package.json...`);
712
- await updatePackageJson(targetPath, useSass);
713
-
714
- await analyzeCentralizedImports(targetPath);
715
-
716
- console.log(`\n📁 Creating required directories...`);
717
- await createRequiredDirectories(targetPath);
718
-
719
- await runYarnInstall(targetPath);
720
-
721
- console.log(`\n📝 Creating injection info...`);
722
- await createInjectionInfo(targetPath);
723
-
724
- console.log(`\n✅ Injection completed successfully!`);
725
- console.log(`\n📋 Next steps:`);
726
- console.log(` 1. cd ${targetPath}`);
727
- console.log(` 2. yarn build # Test the build`);
728
- console.log(` 3. yarn start # Test development mode`);
729
- console.log(
730
- ` 4. yarn acp # Commit changes (or yarn bacp for build+commit)`
731
- );
732
- } catch (error) {
733
- console.error(`\n❌ Injection failed: ${error}`);
734
- throw error;
735
- }
736
- }
1
+ #!/usr/bin/env tsx
2
+
3
+ import fs from 'fs';
4
+ import fsExtra from 'fs-extra';
5
+ import path from 'path';
6
+ import { execSync } from 'child_process';
7
+ import { fileURLToPath } from 'url';
8
+ import { isValidPath, gitExec } from './utils.js';
9
+
10
+ export interface InjectionPlan {
11
+ targetPath: string;
12
+ isObsidianPlugin: boolean;
13
+ hasPackageJson: boolean;
14
+ hasManifest: boolean;
15
+ hasScriptsFolder: boolean;
16
+ currentDependencies: string[];
17
+ }
18
+
19
+ /**
20
+ * Analyze the target plugin directory
21
+ */
22
+ export async function analyzePlugin(pluginPath: string): Promise<InjectionPlan> {
23
+ const packageJsonPath = path.join(pluginPath, 'package.json');
24
+ const manifestPath = path.join(pluginPath, 'manifest.json');
25
+ const scriptsPath = path.join(pluginPath, 'scripts');
26
+
27
+ const plan: InjectionPlan = {
28
+ targetPath: pluginPath,
29
+ isObsidianPlugin: false,
30
+ hasPackageJson: await isValidPath(packageJsonPath),
31
+ hasManifest: await isValidPath(manifestPath),
32
+ hasScriptsFolder: await isValidPath(scriptsPath),
33
+ currentDependencies: []
34
+ };
35
+
36
+ if (plan.hasManifest) {
37
+ try {
38
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
39
+ plan.isObsidianPlugin = !!(manifest.id && manifest.name && manifest.version);
40
+ } catch {
41
+ console.warn('Warning: Could not parse manifest.json');
42
+ }
43
+ }
44
+
45
+ if (plan.hasPackageJson) {
46
+ try {
47
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
48
+ plan.currentDependencies = [
49
+ ...Object.keys(packageJson.dependencies || {}),
50
+ ...Object.keys(packageJson.devDependencies || {})
51
+ ];
52
+ } catch {
53
+ console.warn('Warning: Could not parse package.json');
54
+ }
55
+ }
56
+
57
+ return plan;
58
+ }
59
+
60
+ /**
61
+ * Find plugin-config root directory (handles NPM global installs)
62
+ */
63
+ export function findPluginConfigRoot(): string {
64
+ const scriptDir = path.dirname(fileURLToPath(import.meta.url));
65
+ const npmPackageRoot = path.resolve(scriptDir, '..');
66
+ const npmPackageJson = path.join(npmPackageRoot, 'package.json');
67
+
68
+ if (fs.existsSync(npmPackageJson)) {
69
+ try {
70
+ const packageContent = JSON.parse(fs.readFileSync(npmPackageJson, 'utf8'));
71
+ if (packageContent.name === 'obsidian-plugin-config') {
72
+ return npmPackageRoot;
73
+ }
74
+ } catch {
75
+ // Ignore parsing errors
76
+ }
77
+ }
78
+
79
+ return process.cwd();
80
+ }
81
+
82
+ /**
83
+ * Copy file content from local plugin-config directory
84
+ */
85
+ export function copyFromLocal(filePath: string): string {
86
+ const configRoot = findPluginConfigRoot();
87
+ const sourcePath = path.join(configRoot, filePath);
88
+
89
+ try {
90
+ return fs.readFileSync(sourcePath, 'utf8');
91
+ } catch (error) {
92
+ throw new Error(`Failed to copy ${filePath}: ${error}`);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Check if plugin-config repo is clean and commit if needed
98
+ */
99
+ export async function ensurePluginConfigClean(): Promise<void> {
100
+ const configRoot = findPluginConfigRoot();
101
+ const gitDir = path.join(configRoot, '.git');
102
+
103
+ // Skip git check if not a git repo
104
+ // (e.g. NPM global install)
105
+ if (!fs.existsSync(gitDir)) {
106
+ console.log(`✅ Plugin-config repo is clean` + ` (NPM install, no git check)`);
107
+ return;
108
+ }
109
+
110
+ const originalCwd = process.cwd();
111
+
112
+ try {
113
+ process.chdir(configRoot);
114
+ const gitStatus = execSync('git status --porcelain', { encoding: 'utf8' }).trim();
115
+
116
+ if (gitStatus) {
117
+ console.log(`\n⚠️ Plugin-config has uncommitted changes:`);
118
+ console.log(gitStatus);
119
+ console.log(`\n🔧 Auto-committing changes...`);
120
+
121
+ const msg = '🔧 Update plugin-config templates';
122
+ gitExec('git add -A');
123
+ gitExec(`git commit -m "${msg}"`);
124
+
125
+ try {
126
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', {
127
+ encoding: 'utf8'
128
+ }).trim();
129
+ gitExec(`git push origin ${branch}`);
130
+ console.log(`✅ Changes committed and pushed`);
131
+ } catch {
132
+ try {
133
+ const branch = execSync('git rev-parse --abbrev-ref HEAD', {
134
+ encoding: 'utf8'
135
+ }).trim();
136
+ gitExec(`git push --set-upstream origin ${branch}`);
137
+ console.log(`✅ New branch pushed with upstream`);
138
+ } catch {
139
+ console.log(`⚠️ Committed locally, push failed`);
140
+ }
141
+ }
142
+ } else {
143
+ console.log(`✅ Plugin-config repo is clean`);
144
+ }
145
+ } finally {
146
+ process.chdir(originalCwd);
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Display injection plan and ask for confirmation
152
+ */
153
+ export async function showInjectionPlan(
154
+ plan: InjectionPlan,
155
+ autoConfirm: boolean = false,
156
+ useSass: boolean = false
157
+ ): Promise<boolean> {
158
+ const { askConfirmation, createReadlineInterface } = await import('./utils.js');
159
+ const rl = createReadlineInterface();
160
+
161
+ console.log(`\n🎯 Injection Plan for: ${plan.targetPath}`);
162
+ console.log(`📁 Target: ${path.basename(plan.targetPath)}`);
163
+ console.log(`📦 Package.json: ${plan.hasPackageJson ? '✅' : '❌'}`);
164
+ console.log(`📋 Manifest.json: ${plan.hasManifest ? '✅' : '❌'}`);
165
+ console.log(
166
+ `📂 Scripts folder: ${plan.hasScriptsFolder ? '✅ (will be updated)' : '❌ (will be created)'}`
167
+ );
168
+ console.log(`🔌 Obsidian plugin: ${plan.isObsidianPlugin ? '✅' : '❌'}`);
169
+ console.log(
170
+ `🎨 SASS support: ${useSass ? '✅ (esbuild-sass-plugin will be added)' : '❌'}`
171
+ );
172
+
173
+ if (!plan.isObsidianPlugin) {
174
+ console.log(`\n⚠️ Warning: This doesn't appear to be a valid Obsidian plugin`);
175
+ console.log(` Missing manifest.json or invalid structure`);
176
+ }
177
+
178
+ console.log(`\n📋 Will inject:`);
179
+ console.log(` ✅ Local scripts (utils.ts, esbuild.config.ts, acp.ts, etc.)`);
180
+ console.log(` ✅ Updated package.json scripts`);
181
+ console.log(` Required dependencies`);
182
+ console.log(` 🔍 Analyze centralized imports (manual commenting may be needed)`);
183
+
184
+ if (autoConfirm) {
185
+ console.log(`\n✅ Auto-confirming injection...`);
186
+ rl.close();
187
+ return true;
188
+ }
189
+
190
+ const result = await askConfirmation(`\nProceed with injection?`, rl);
191
+ rl.close();
192
+ return result;
193
+ }
194
+
195
+ /**
196
+ * Clean old script files
197
+ */
198
+ export async function cleanOldScripts(scriptsPath: string): Promise<void> {
199
+ const scriptNames = [
200
+ 'utils',
201
+ 'esbuild.config',
202
+ 'acp',
203
+ 'update-version',
204
+ 'release',
205
+ 'help'
206
+ ];
207
+ const extensions = ['.ts', '.mts', '.js', '.mjs'];
208
+
209
+ for (const scriptName of scriptNames) {
210
+ for (const ext of extensions) {
211
+ const scriptFile = path.join(scriptsPath, `${scriptName}${ext}`);
212
+ if (await isValidPath(scriptFile)) {
213
+ fs.unlinkSync(scriptFile);
214
+ console.log(
215
+ `🗑️ Removed existing ${scriptName}${ext} (will be replaced)`
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ const obsoleteRootFiles = ['help-plugin.ts'];
222
+ for (const fileName of obsoleteRootFiles) {
223
+ const filePath = path.join(path.dirname(scriptsPath), fileName);
224
+ if (await isValidPath(filePath)) {
225
+ fs.unlinkSync(filePath);
226
+ console.log(`🗑️ Removed obsolete root file: ${fileName}`);
227
+ }
228
+ }
229
+
230
+ const obsoleteFiles = ['start.mjs', 'start.js'];
231
+ for (const fileName of obsoleteFiles) {
232
+ const filePath = path.join(scriptsPath, fileName);
233
+ if (await isValidPath(filePath)) {
234
+ fs.unlinkSync(filePath);
235
+ console.log(`🗑️ Removed obsolete file: ${fileName}`);
236
+ }
237
+ }
238
+ }
239
+
240
+ /**
241
+ * Clean old ESLint config files
242
+ */
243
+ export async function cleanOldLintFiles(targetPath: string): Promise<void> {
244
+ const oldLintFiles = ['.eslintrc', '.eslintrc.js', '.eslintrc.json', '.eslintignore'];
245
+ const conflictingLintFiles = [
246
+ 'eslint.config.ts',
247
+ 'eslint.config.cjs',
248
+ 'eslint.config.js',
249
+ 'eslint.config.mjs'
250
+ ];
251
+
252
+ for (const fileName of oldLintFiles) {
253
+ const filePath = path.join(targetPath, fileName);
254
+ if (await isValidPath(filePath)) {
255
+ fs.unlinkSync(filePath);
256
+ console.log(
257
+ `🗑️ Removed old ESLint file: ${fileName} (replaced by eslint.config.ts)`
258
+ );
259
+ }
260
+ }
261
+
262
+ for (const fileName of conflictingLintFiles) {
263
+ const filePath = path.join(targetPath, fileName);
264
+ if (await isValidPath(filePath)) {
265
+ fs.unlinkSync(filePath);
266
+ console.log(
267
+ `🗑️ Removed existing ESLint file: ${fileName} (will be replaced by injection)`
268
+ );
269
+ }
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Inject scripts and config files
275
+ */
276
+ export async function injectScripts(targetPath: string): Promise<void> {
277
+ const scriptsPath = path.join(targetPath, 'scripts');
278
+
279
+ if (!(await isValidPath(scriptsPath))) {
280
+ fs.mkdirSync(scriptsPath, { recursive: true });
281
+ console.log(`📁 Created scripts directory`);
282
+ }
283
+
284
+ await cleanOldScripts(scriptsPath);
285
+ await cleanOldLintFiles(targetPath);
286
+
287
+ const scriptFiles = [
288
+ 'templates/scripts/utils.ts',
289
+ 'templates/scripts/esbuild.config.ts',
290
+ 'templates/scripts/acp.ts',
291
+ 'templates/scripts/update-version.ts',
292
+ 'templates/scripts/release.ts',
293
+ 'templates/scripts/help.ts'
294
+ ];
295
+
296
+ // Files that need value-preserving merge instead
297
+ // of full overwrite (user fills in their paths)
298
+ const mergeEnvFile = new Set(['.env']);
299
+
300
+ // Files with .template suffix (NPM excludes dotfiles)
301
+ // Map: { source: targetName }
302
+ const configFileMap: Record<string, string> = {
303
+ 'templates/tsconfig.json': 'tsconfig.json',
304
+ 'templates/gitignore.template': '.gitignore',
305
+ 'templates/eslint.config.mts': 'eslint.config.mts',
306
+ 'templates/.editorconfig': '.editorconfig',
307
+ 'templates/.prettierrc': '.prettierrc',
308
+ 'templates/npmrc.template': '.npmrc',
309
+ 'templates/env.template': '.env'
310
+ };
311
+
312
+ const configVscodeMap: Record<string, string> = {
313
+ 'templates/.vscode/settings.json': '.vscode/settings.json',
314
+ 'templates/.vscode/tasks.json': '.vscode/tasks.json'
315
+ };
316
+
317
+ const workflowFiles = [
318
+ 'templates/.github/workflows/release.yml',
319
+ 'templates/.github/workflows/release-body.md'
320
+ ];
321
+
322
+ console.log(`\n📥 Copying scripts from local files...`);
323
+
324
+ for (const scriptFile of scriptFiles) {
325
+ try {
326
+ const content = copyFromLocal(scriptFile);
327
+ const fileName = path.basename(scriptFile);
328
+ const targetFile = path.join(scriptsPath, fileName);
329
+ fs.writeFileSync(targetFile, content, 'utf8');
330
+ console.log(` ✅ ${fileName}`);
331
+ } catch (error) {
332
+ console.error(` ❌ Failed to inject ${scriptFile}: ${error}`);
333
+ }
334
+ }
335
+
336
+ console.log(`\n📥 Copying config files...`);
337
+
338
+ // Copy root config files
339
+ for (const [src, destName] of Object.entries(configFileMap)) {
340
+ try {
341
+ const targetFile = path.join(targetPath, destName);
342
+ const templateContent = copyFromLocal(src);
343
+
344
+ // For .env: merge existing values into the template
345
+ if (mergeEnvFile.has(destName) && fs.existsSync(targetFile)) {
346
+ const existing = fs.readFileSync(targetFile, 'utf8');
347
+ // Parse existing key=value pairs
348
+ const existingVals: Record<string, string> = {};
349
+ for (const line of existing.split(/\r?\n/)) {
350
+ const m = line.match(/^([^#=]+)=(.*)$/);
351
+ if (m) existingVals[m[1].trim()] = m[2].trim();
352
+ }
353
+ // Re-write template, substituting existing values
354
+ const merged = templateContent
355
+ .split(/\r?\n/)
356
+ .map((line) => {
357
+ const m = line.match(/^([^#=]+)=(.*)$/);
358
+ if (m) {
359
+ const key = m[1].trim();
360
+ const val = existingVals[key] ?? m[2].trim();
361
+ return `${key}=${val}`;
362
+ }
363
+ return line;
364
+ })
365
+ .join('\n');
366
+ fs.writeFileSync(targetFile, merged, 'utf8');
367
+ console.log(` ✅ ${destName} (values preserved)`);
368
+ continue;
369
+ }
370
+
371
+ fs.writeFileSync(targetFile, templateContent, 'utf8');
372
+ console.log(` ✅ ${destName}`);
373
+ } catch (error) {
374
+ console.error(` ❌ Failed to inject ${destName}: ${error}`);
375
+ }
376
+ }
377
+
378
+ // Copy .vscode config files
379
+ for (const [src, destName] of Object.entries(configVscodeMap)) {
380
+ try {
381
+ const content = copyFromLocal(src);
382
+ const targetFile = path.join(targetPath, destName);
383
+ const targetDir = path.dirname(targetFile);
384
+ if (!(await isValidPath(targetDir))) {
385
+ fs.mkdirSync(targetDir, { recursive: true });
386
+ }
387
+ fs.writeFileSync(targetFile, content, 'utf8');
388
+ console.log(` ✅ ${destName}`);
389
+ } catch (error) {
390
+ console.error(` ❌ Failed to inject ${destName}: ${error}`);
391
+ }
392
+ }
393
+
394
+ console.log(`\n📥 Copying GitHub workflows from local files...`);
395
+
396
+ for (const workflowFile of workflowFiles) {
397
+ try {
398
+ const content = copyFromLocal(workflowFile);
399
+ const relativePath = workflowFile.replace('templates/', '');
400
+ const targetFile = path.join(targetPath, relativePath);
401
+ const targetDir = path.dirname(targetFile);
402
+
403
+ if (!(await isValidPath(targetDir))) {
404
+ fs.mkdirSync(targetDir, { recursive: true });
405
+ }
406
+
407
+ fs.writeFileSync(targetFile, content, 'utf8');
408
+ console.log(` ✅ ${relativePath}`);
409
+ } catch (error) {
410
+ console.error(` ❌ Failed to inject ${workflowFile}: ${error}`);
411
+ }
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Update package.json with autonomous configuration
417
+ */
418
+ export async function updatePackageJson(
419
+ targetPath: string,
420
+ useSass: boolean = false
421
+ ): Promise<void> {
422
+ const packageJsonPath = path.join(targetPath, 'package.json');
423
+
424
+ if (!(await isValidPath(packageJsonPath))) {
425
+ console.log(`❌ No package.json found, skipping package.json update`);
426
+ return;
427
+ }
428
+
429
+ try {
430
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
431
+
432
+ const configRoot = findPluginConfigRoot();
433
+ const templatePkg = JSON.parse(
434
+ fs.readFileSync(path.join(configRoot, 'templates/package.json'), 'utf8')
435
+ );
436
+
437
+ if (useSass) {
438
+ const sassPkg = JSON.parse(
439
+ fs.readFileSync(
440
+ path.join(configRoot, 'templates/package-sass.json'),
441
+ 'utf8'
442
+ )
443
+ );
444
+ Object.assign(templatePkg.devDependencies, sassPkg.devDependencies);
445
+ }
446
+
447
+ const obsoleteScripts = ['version'];
448
+ for (const script of obsoleteScripts) {
449
+ if (packageJson.scripts?.[script]) {
450
+ console.log(` 🧹 Removing obsolete script: "${script}"`);
451
+ delete packageJson.scripts[script];
452
+ }
453
+ }
454
+
455
+ packageJson.scripts = {
456
+ ...packageJson.scripts,
457
+ ...templatePkg.scripts
458
+ };
459
+
460
+ if (!packageJson.devDependencies) packageJson.devDependencies = {};
461
+
462
+ const requiredDeps: Record<string, string> = templatePkg.devDependencies;
463
+
464
+ let addedDeps = 0;
465
+ let updatedDeps = 0;
466
+ for (const [dep, version] of Object.entries(requiredDeps)) {
467
+ if (!packageJson.devDependencies[dep]) {
468
+ packageJson.devDependencies[dep] = version as string;
469
+ addedDeps++;
470
+ } else if (packageJson.devDependencies[dep] !== version) {
471
+ packageJson.devDependencies[dep] = version as string;
472
+ updatedDeps++;
473
+ }
474
+ }
475
+
476
+ if (!packageJson.engines) packageJson.engines = {};
477
+ packageJson.engines.npm = templatePkg.engines.npm;
478
+ packageJson.engines.yarn = templatePkg.engines.yarn;
479
+ packageJson.type = templatePkg.type;
480
+
481
+ fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2), 'utf8');
482
+ console.log(
483
+ ` ✅ Updated package.json (${addedDeps} new, ${updatedDeps} updated dependencies)`
484
+ );
485
+ } catch (error) {
486
+ console.error(` ❌ Failed to update package.json: ${error}`);
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Analyze centralized imports in source files (without modifying)
492
+ */
493
+ export async function analyzeCentralizedImports(targetPath: string): Promise<void> {
494
+ const srcPath = path.join(targetPath, 'src');
495
+
496
+ if (!(await isValidPath(srcPath))) {
497
+ console.log(` ℹ️ No src directory found`);
498
+ return;
499
+ }
500
+
501
+ console.log(`\n🔍 Analyzing centralized imports...`);
502
+
503
+ try {
504
+ const findTsFiles = (dir: string): string[] => {
505
+ const files: string[] = [];
506
+ for (const item of fs.readdirSync(dir)) {
507
+ const fullPath = path.join(dir, item);
508
+ if (fs.statSync(fullPath).isDirectory()) {
509
+ files.push(...findTsFiles(fullPath));
510
+ } else if (item.endsWith('.ts') || item.endsWith('.tsx')) {
511
+ files.push(fullPath);
512
+ }
513
+ }
514
+ return files;
515
+ };
516
+
517
+ const tsFiles = findTsFiles(srcPath);
518
+ let filesWithImports = 0;
519
+
520
+ for (const filePath of tsFiles) {
521
+ try {
522
+ const content = fs.readFileSync(filePath, 'utf8');
523
+ const importRegex =
524
+ /import\s+.*from\s+["']obsidian-plugin-config[^"']*["']/g;
525
+ if (importRegex.test(content)) {
526
+ filesWithImports++;
527
+ console.log(
528
+ ` ⚠️ ${path.relative(targetPath, filePath)} - contains centralized imports`
529
+ );
530
+ }
531
+ } catch (error) {
532
+ console.warn(
533
+ ` ⚠️ Could not analyze ${path.relative(targetPath, filePath)}: ${error}`
534
+ );
535
+ }
536
+ }
537
+
538
+ if (filesWithImports === 0) {
539
+ console.log(` ✅ No centralized imports found`);
540
+ } else {
541
+ console.log(
542
+ ` ⚠️ Found ${filesWithImports} files with centralized imports`
543
+ );
544
+ console.log(
545
+ ` 💡 You may need to manually comment these imports for the plugin to work`
546
+ );
547
+ }
548
+ } catch (error) {
549
+ console.error(` ❌ Failed to analyze imports: ${error}`);
550
+ }
551
+ }
552
+
553
+ /**
554
+ * Create required directories
555
+ */
556
+ export async function createRequiredDirectories(targetPath: string): Promise<void> {
557
+ const directories = [path.join(targetPath, '.github', 'workflows')];
558
+
559
+ for (const dir of directories) {
560
+ if (!(await isValidPath(dir))) {
561
+ fs.mkdirSync(dir, { recursive: true });
562
+ console.log(` 📁 Created ${path.relative(targetPath, dir)}`);
563
+ }
564
+ }
565
+ }
566
+
567
+ /**
568
+ * Create injection info file
569
+ */
570
+ export async function createInjectionInfo(targetPath: string): Promise<void> {
571
+ const configRoot = findPluginConfigRoot();
572
+ const configPackageJsonPath = path.join(configRoot, 'package.json');
573
+
574
+ let injectorVersion = 'unknown';
575
+ try {
576
+ const configPackageJson = JSON.parse(
577
+ fs.readFileSync(configPackageJsonPath, 'utf8')
578
+ );
579
+ injectorVersion = configPackageJson.version || 'unknown';
580
+ } catch {
581
+ console.warn('Warning: Could not read injector version');
582
+ }
583
+
584
+ const injectionInfo = {
585
+ injectorVersion,
586
+ injectionDate: new Date().toISOString(),
587
+ injectorName: 'obsidian-plugin-config'
588
+ };
589
+
590
+ const infoPath = path.join(targetPath, '.injection-info.json');
591
+ fs.writeFileSync(infoPath, JSON.stringify(injectionInfo, null, 2));
592
+ console.log(` ✅ Created injection info file (.injection-info.json)`);
593
+ }
594
+
595
+ /**
596
+ * Read injection info from target plugin
597
+ */
598
+ export function readInjectionInfo(targetPath: string): Record<string, string> | null {
599
+ const infoPath = path.join(targetPath, '.injection-info.json');
600
+
601
+ if (!fs.existsSync(infoPath)) return null;
602
+
603
+ try {
604
+ return JSON.parse(fs.readFileSync(infoPath, 'utf8'));
605
+ } catch {
606
+ console.warn('Warning: Could not parse .injection-info.json');
607
+ return null;
608
+ }
609
+ }
610
+
611
+ /**
612
+ * Clean NPM/Yarn lock files and node_modules to ensure fresh install
613
+ */
614
+ export async function cleanNpmArtifactsIfNeeded(targetPath: string): Promise<void> {
615
+ const packageLockPath = path.join(targetPath, 'package-lock.json');
616
+ const yarnLockPath = path.join(targetPath, 'yarn.lock');
617
+ const nodeModulesPath = path.join(targetPath, 'node_modules');
618
+
619
+ const hasPackageLock = fs.existsSync(packageLockPath);
620
+ const hasYarnLock = fs.existsSync(yarnLockPath);
621
+
622
+ if (hasPackageLock || hasYarnLock) {
623
+ console.log(`\n🧹 Cleaning lock files and node_modules...`);
624
+
625
+ try {
626
+ if (hasPackageLock) {
627
+ fs.unlinkSync(packageLockPath);
628
+ console.log(` 🗑️ Removed package-lock.json`);
629
+ }
630
+
631
+ if (hasYarnLock) {
632
+ fs.unlinkSync(yarnLockPath);
633
+ console.log(` 🗑️ Removed yarn.lock`);
634
+ }
635
+
636
+ if (fs.existsSync(nodeModulesPath)) {
637
+ // Use fs-extra for better Windows compatibility with locked files
638
+ await fsExtra.remove(nodeModulesPath);
639
+ console.log(
640
+ ` 🗑️ Removed node_modules (will be reinstalled with Yarn)`
641
+ );
642
+ }
643
+
644
+ console.log(` Lock files and artifacts cleaned for fresh install`);
645
+ } catch (error) {
646
+ console.error(` Failed to clean artifacts: ${error}`);
647
+ console.log(
648
+ ` 💡 You may need to manually remove package-lock.json, yarn.lock and node_modules`
649
+ );
650
+ }
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Check if tsx is installed locally and install it if needed
656
+ */
657
+ export async function ensureTsxInstalled(targetPath: string): Promise<void> {
658
+ console.log(`\n🔍 Checking tsx installation...`);
659
+
660
+ const packageJsonPath = path.join(targetPath, 'package.json');
661
+
662
+ try {
663
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
664
+ const devDependencies = packageJson.devDependencies || {};
665
+ const dependencies = packageJson.dependencies || {};
666
+
667
+ if (devDependencies.tsx || dependencies.tsx) {
668
+ console.log(` ✅ tsx is already installed`);
669
+ return;
670
+ }
671
+
672
+ console.log(` ⚠️ tsx not found, installing as dev dependency...`);
673
+ execSync('yarn add -D tsx', { cwd: targetPath, stdio: 'inherit' });
674
+ console.log(` tsx installed successfully`);
675
+ } catch (error) {
676
+ console.error(` ❌ Failed to install tsx: ${error}`);
677
+ console.log(` 💡 You may need to install tsx manually: yarn add -D tsx`);
678
+ throw new Error('tsx installation failed');
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Run yarn install in target directory
684
+ */
685
+ export async function runYarnInstall(targetPath: string): Promise<void> {
686
+ console.log(`\n📦 Installing dependencies...`);
687
+
688
+ try {
689
+ execSync('yarn install', { cwd: targetPath, stdio: 'inherit' });
690
+ console.log(` Dependencies installed successfully`);
691
+ } catch (error) {
692
+ console.error(` Failed to install dependencies: ${error}`);
693
+ console.log(
694
+ ` 💡 You may need to run 'yarn install' manually in the target directory`
695
+ );
696
+ }
697
+ }
698
+
699
+ /**
700
+ * Main injection orchestration function
701
+ */
702
+ export async function performInjection(
703
+ targetPath: string,
704
+ useSass: boolean = false
705
+ ): Promise<void> {
706
+ console.log(`\n🚀 Starting injection process...`);
707
+
708
+ try {
709
+ await cleanNpmArtifactsIfNeeded(targetPath);
710
+ await ensureTsxInstalled(targetPath);
711
+ await injectScripts(targetPath);
712
+
713
+ console.log(`\n📦 Updating package.json...`);
714
+ await updatePackageJson(targetPath, useSass);
715
+
716
+ await analyzeCentralizedImports(targetPath);
717
+
718
+ console.log(`\n📁 Creating required directories...`);
719
+ await createRequiredDirectories(targetPath);
720
+
721
+ await runYarnInstall(targetPath);
722
+
723
+ console.log(`\n📝 Creating injection info...`);
724
+ await createInjectionInfo(targetPath);
725
+
726
+ console.log(`\n✅ Injection completed successfully!`);
727
+ console.log(`\n📋 Next steps:`);
728
+ console.log(` 1. cd ${targetPath}`);
729
+ console.log(` 2. yarn build # Test the build`);
730
+ console.log(` 3. yarn start # Test development mode`);
731
+ console.log(
732
+ ` 4. yarn acp # Commit changes (or yarn bacp for build+commit)`
733
+ );
734
+ } catch (error) {
735
+ console.error(`\n❌ Injection failed: ${error}`);
736
+ throw error;
737
+ }
738
+ }