forked from jackwener/OpenCLI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
1533 lines (1335 loc) · 45.8 KB
/
plugin.ts
File metadata and controls
1533 lines (1335 loc) · 45.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Plugin management: install, uninstall, and list plugins.
*
* Plugins live in ~/.opencli/plugins/<name>/.
* Monorepo clones live in ~/.opencli/monorepos/<repo-name>/.
* Install source format: "github:user/repo", "github:user/repo/subplugin",
* "https://github.com/user/repo", "file:///local/plugin", or a local directory path.
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { execSync, execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { PLUGINS_DIR } from './discovery.js';
import { getErrorMessage } from './errors.js';
import { log } from './logger.js';
import {
readPluginManifest,
isMonorepo,
getEnabledPlugins,
checkCompatibility,
type PluginManifest,
} from './plugin-manifest.js';
import { getUserPluginLockFilePath, USER_MONOREPOS_DIR } from './user-opencli-paths.js';
const isWindows = process.platform === 'win32';
const LOCAL_PLUGIN_SOURCE_PREFIX = 'local:';
/** Path to the lock file that tracks installed plugin versions. */
export function getLockFilePath(): string {
return getUserPluginLockFilePath();
}
/** Monorepo clones directory: ~/.opencli/monorepos/ */
export function getMonoreposDir(): string {
return USER_MONOREPOS_DIR;
}
export type PluginSourceRecord =
| { kind: 'git'; url: string }
| { kind: 'local'; path: string }
| { kind: 'monorepo'; url: string; repoName: string; subPath: string };
export interface LockEntry {
source: PluginSourceRecord;
commitHash: string;
installedAt: string;
updatedAt?: string;
}
export interface PluginInfo {
name: string;
path: string;
commands: string[];
source?: string;
version?: string;
installedAt?: string;
/** If from a monorepo, the monorepo name. */
monorepoName?: string;
/** Description from opencli-plugin.json. */
description?: string;
}
interface ParsedSource {
type: 'git' | 'local';
name: string;
subPlugin?: string;
cloneUrl?: string;
localPath?: string;
}
function parseStoredPluginSource(source?: string): PluginSourceRecord | undefined {
if (!source) return undefined;
if (source.startsWith(LOCAL_PLUGIN_SOURCE_PREFIX)) {
return {
kind: 'local',
path: path.resolve(source.slice(LOCAL_PLUGIN_SOURCE_PREFIX.length)),
};
}
return { kind: 'git', url: source };
}
function isLocalPluginSource(source?: string): boolean {
return parseStoredPluginSource(source)?.kind === 'local';
}
function toStoredPluginSource(source: PluginSourceRecord): string {
if (source.kind === 'local') {
return `${LOCAL_PLUGIN_SOURCE_PREFIX}${path.resolve(source.path)}`;
}
return source.url;
}
function toLocalPluginSource(pluginDir: string): string {
return toStoredPluginSource({ kind: 'local', path: pluginDir });
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function normalizeLegacyMonorepo(
value: unknown,
): { name: string; subPath: string } | undefined {
if (!isRecord(value)) return undefined;
if (typeof value.name !== 'string' || typeof value.subPath !== 'string') return undefined;
return { name: value.name, subPath: value.subPath };
}
function normalizePluginSource(
source: unknown,
legacyMonorepo?: { name: string; subPath: string },
): PluginSourceRecord | undefined {
if (typeof source === 'string') {
const parsed = parseStoredPluginSource(source);
if (!parsed) return undefined;
if (parsed.kind === 'git' && legacyMonorepo) {
return {
kind: 'monorepo',
url: parsed.url,
repoName: legacyMonorepo.name,
subPath: legacyMonorepo.subPath,
};
}
return parsed;
}
if (!isRecord(source) || typeof source.kind !== 'string') return undefined;
switch (source.kind) {
case 'git':
return typeof source.url === 'string'
? { kind: 'git', url: source.url }
: undefined;
case 'local':
return typeof source.path === 'string'
? { kind: 'local', path: path.resolve(source.path) }
: undefined;
case 'monorepo':
return typeof source.url === 'string'
&& typeof source.repoName === 'string'
&& typeof source.subPath === 'string'
? {
kind: 'monorepo',
url: source.url,
repoName: source.repoName,
subPath: source.subPath,
}
: undefined;
default:
return undefined;
}
}
function normalizeLockEntry(value: unknown): LockEntry | undefined {
if (!isRecord(value)) return undefined;
const legacyMonorepo = normalizeLegacyMonorepo(value.monorepo);
const source = normalizePluginSource(value.source, legacyMonorepo);
if (!source) return undefined;
if (typeof value.commitHash !== 'string' || typeof value.installedAt !== 'string') {
return undefined;
}
const entry: LockEntry = {
source,
commitHash: value.commitHash,
installedAt: value.installedAt,
};
if (typeof value.updatedAt === 'string') {
entry.updatedAt = value.updatedAt;
}
return entry;
}
function resolvePluginSource(lockEntry: LockEntry | undefined, pluginDir: string): PluginSourceRecord | undefined {
if (lockEntry) {
return lockEntry.source;
}
return parseStoredPluginSource(getPluginSource(pluginDir));
}
function resolveStoredPluginSource(lockEntry: LockEntry | undefined, pluginDir: string): string | undefined {
const source = resolvePluginSource(lockEntry, pluginDir);
return source ? toStoredPluginSource(source) : undefined;
}
// ── Filesystem helpers ──────────────────────────────────────────────────────
/**
* Move a directory, with EXDEV fallback.
* fs.renameSync fails when source and destination are on different
* filesystems (e.g. /tmp → ~/.opencli). In that case we copy then remove.
*/
type MoveDirFsOps = Pick<typeof fs, 'renameSync' | 'cpSync' | 'rmSync'>;
function moveDir(src: string, dest: string, fsOps: MoveDirFsOps = fs): void {
try {
fsOps.renameSync(src, dest);
} catch (err: unknown) {
if ((err as NodeJS.ErrnoException).code === 'EXDEV') {
try {
fsOps.cpSync(src, dest, { recursive: true });
} catch (copyErr) {
try { fsOps.rmSync(dest, { recursive: true, force: true }); } catch {}
throw copyErr;
}
fsOps.rmSync(src, { recursive: true, force: true });
} else {
throw err;
}
}
}
type PromoteDirFsOps = MoveDirFsOps & Pick<typeof fs, 'existsSync' | 'mkdirSync'>;
function createSiblingTempPath(dest: string, kind: 'tmp' | 'bak'): string {
const suffix = `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
return path.join(path.dirname(dest), `.${path.basename(dest)}.${kind}-${suffix}`);
}
/**
* Promote a prepared staging directory into its final location.
* The final path is only exposed after the directory has been fully prepared.
*/
function promoteDir(stagingDir: string, dest: string, fsOps: PromoteDirFsOps = fs): void {
if (fsOps.existsSync(dest)) {
throw new Error(`Destination already exists: ${dest}`);
}
fsOps.mkdirSync(path.dirname(dest), { recursive: true });
const tempDest = createSiblingTempPath(dest, 'tmp');
try {
moveDir(stagingDir, tempDest, fsOps);
fsOps.renameSync(tempDest, dest);
} catch (err) {
try { fsOps.rmSync(tempDest, { recursive: true, force: true }); } catch {}
throw err;
}
}
function replaceDir(stagingDir: string, dest: string, fsOps: PromoteDirFsOps = fs): void {
const replacement = beginReplaceDir(stagingDir, dest, fsOps);
replacement.finalize();
}
function cloneRepoToTemp(cloneUrl: string): string {
const tmpCloneDir = path.join(
os.tmpdir(),
`opencli-clone-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`,
);
try {
execFileSync('git', ['clone', '--depth', '1', cloneUrl, tmpCloneDir], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (err) {
throw new Error(`Failed to clone plugin: ${getErrorMessage(err)}`);
}
return tmpCloneDir;
}
function withTempClone<T>(cloneUrl: string, work: (cloneDir: string) => T): T {
const tmpCloneDir = cloneRepoToTemp(cloneUrl);
try {
return work(tmpCloneDir);
} finally {
try { fs.rmSync(tmpCloneDir, { recursive: true, force: true }); } catch {}
}
}
function resolveRemotePluginSource(lockEntry: LockEntry | undefined, dir: string): string {
const source = resolvePluginSource(lockEntry, dir);
if (!source || source.kind === 'local') {
throw new Error(`Unable to determine remote source for plugin at ${dir}`);
}
return source.url;
}
function pathExistsSync(p: string): boolean {
try {
fs.lstatSync(p);
return true;
} catch {
return false;
}
}
function removePathSync(p: string): void {
try {
const stat = fs.lstatSync(p);
if (stat.isSymbolicLink()) {
fs.unlinkSync(p);
return;
}
fs.rmSync(p, { recursive: true, force: true });
} catch {}
}
interface TransactionHandle {
finalize(): void;
rollback(): void;
}
class Transaction {
#handles: TransactionHandle[] = [];
#settled = false;
track<T extends TransactionHandle>(handle: T): T {
this.#handles.push(handle);
return handle;
}
commit(): void {
if (this.#settled) return;
this.#settled = true;
for (const handle of this.#handles) {
handle.finalize();
}
}
rollback(): void {
if (this.#settled) return;
this.#settled = true;
for (const handle of [...this.#handles].reverse()) {
handle.rollback();
}
}
}
function runTransaction<T>(work: (tx: Transaction) => T): T {
const tx = new Transaction();
try {
const result = work(tx);
tx.commit();
return result;
} catch (err) {
tx.rollback();
throw err;
}
}
function beginReplaceDir(
stagingDir: string,
dest: string,
fsOps: PromoteDirFsOps = fs,
): TransactionHandle {
const destExisted = fsOps.existsSync(dest);
fsOps.mkdirSync(path.dirname(dest), { recursive: true });
const tempDest = createSiblingTempPath(dest, 'tmp');
const backupDest = destExisted ? createSiblingTempPath(dest, 'bak') : null;
let settled = false;
try {
moveDir(stagingDir, tempDest, fsOps);
if (backupDest) {
fsOps.renameSync(dest, backupDest);
}
fsOps.renameSync(tempDest, dest);
} catch (err) {
try { fsOps.rmSync(tempDest, { recursive: true, force: true }); } catch {}
if (backupDest && !fsOps.existsSync(dest)) {
try { fsOps.renameSync(backupDest, dest); } catch {}
}
throw err;
}
return {
finalize() {
if (settled) return;
settled = true;
if (backupDest) {
try { fsOps.rmSync(backupDest, { recursive: true, force: true }); } catch {}
}
},
rollback() {
if (settled) return;
settled = true;
try { fsOps.rmSync(dest, { recursive: true, force: true }); } catch {}
if (backupDest) {
try { fsOps.renameSync(backupDest, dest); } catch {}
}
try { fsOps.rmSync(tempDest, { recursive: true, force: true }); } catch {}
},
};
}
function beginReplaceSymlink(target: string, linkPath: string): TransactionHandle {
const linkExists = pathExistsSync(linkPath);
if (linkExists && !isSymlinkSync(linkPath)) {
throw new Error(`Expected monorepo plugin link at ${linkPath} to be a symlink`);
}
fs.mkdirSync(path.dirname(linkPath), { recursive: true });
const tempLink = createSiblingTempPath(linkPath, 'tmp');
const backupLink = linkExists ? createSiblingTempPath(linkPath, 'bak') : null;
const linkType = isWindows ? 'junction' : 'dir';
let settled = false;
try {
fs.symlinkSync(target, tempLink, linkType);
if (backupLink) {
fs.renameSync(linkPath, backupLink);
}
fs.renameSync(tempLink, linkPath);
} catch (err) {
removePathSync(tempLink);
if (backupLink && !pathExistsSync(linkPath)) {
try { fs.renameSync(backupLink, linkPath); } catch {}
}
throw err;
}
return {
finalize() {
if (settled) return;
settled = true;
if (backupLink) {
removePathSync(backupLink);
}
},
rollback() {
if (settled) return;
settled = true;
removePathSync(linkPath);
if (backupLink && !pathExistsSync(linkPath)) {
try { fs.renameSync(backupLink, linkPath); } catch {}
}
removePathSync(tempLink);
},
};
}
// ── Validation helpers ──────────────────────────────────────────────────────
export interface ValidationResult {
valid: boolean;
errors: string[];
}
// ── Lock file helpers ───────────────────────────────────────────────────────
function readLockFileWithWriter(
writeLock: (lock: Record<string, LockEntry>) => void = writeLockFile,
): Record<string, LockEntry> {
try {
const raw = fs.readFileSync(getLockFilePath(), 'utf-8');
const parsed = JSON.parse(raw) as unknown;
if (!isRecord(parsed)) return {};
const lock: Record<string, LockEntry> = {};
let changed = false;
for (const [name, entry] of Object.entries(parsed)) {
const normalized = normalizeLockEntry(entry);
if (!normalized) {
changed = true;
continue;
}
lock[name] = normalized;
if (JSON.stringify(entry) !== JSON.stringify(normalized)) {
changed = true;
}
}
if (changed) {
try {
writeLock(lock);
} catch {}
}
return lock;
} catch {
return {};
}
}
export function readLockFile(): Record<string, LockEntry> {
return readLockFileWithWriter(writeLockFile);
}
type WriteLockFileFsOps = Pick<typeof fs, 'mkdirSync' | 'writeFileSync' | 'renameSync' | 'rmSync'>;
function writeLockFileWithFs(
lock: Record<string, LockEntry>,
fsOps: WriteLockFileFsOps = fs,
): void {
const lockPath = getLockFilePath();
fsOps.mkdirSync(path.dirname(lockPath), { recursive: true });
const tempPath = createSiblingTempPath(lockPath, 'tmp');
try {
fsOps.writeFileSync(tempPath, JSON.stringify(lock, null, 2) + '\n');
fsOps.renameSync(tempPath, lockPath);
} catch (err) {
try { fsOps.rmSync(tempPath, { force: true }); } catch {}
throw err;
}
}
export function writeLockFile(lock: Record<string, LockEntry>): void {
writeLockFileWithFs(lock, fs);
}
/** Get the HEAD commit hash of a git repo directory. */
export function getCommitHash(dir: string): string | undefined {
try {
return execFileSync('git', ['rev-parse', 'HEAD'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
}).trim();
} catch {
return undefined;
}
}
/**
* Validate that a downloaded plugin directory is a structurally valid plugin.
* Checks for at least one command file (.yaml, .yml, .ts, .js) and a valid
* package.json if it contains .ts files.
*/
export function validatePluginStructure(pluginDir: string): ValidationResult {
const errors: string[] = [];
if (!fs.existsSync(pluginDir)) {
return { valid: false, errors: ['Plugin directory does not exist'] };
}
const files = fs.readdirSync(pluginDir);
const hasYaml = files.some(f => f.endsWith('.yaml') || f.endsWith('.yml'));
const hasTs = files.some(f => f.endsWith('.ts') && !f.endsWith('.d.ts') && !f.endsWith('.test.ts'));
const hasJs = files.some(f => f.endsWith('.js') && !f.endsWith('.d.js'));
if (!hasYaml && !hasTs && !hasJs) {
errors.push('No command files found in plugin directory. A plugin must contain at least one .yaml, .ts, or .js command file.');
}
if (hasTs) {
const pkgJsonPath = path.join(pluginDir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) {
errors.push('Plugin contains .ts files but no package.json. A package.json with "type": "module" and "@jackwener/opencli" peer dependency is required for TS plugins.');
} else {
try {
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8'));
if (pkg.type !== 'module') {
errors.push('Plugin package.json must have "type": "module" for TypeScript plugins.');
}
} catch {
errors.push('Plugin package.json is malformed or invalid JSON.');
}
}
}
return { valid: errors.length === 0, errors };
}
function installDependencies(dir: string): void {
const pkgJsonPath = path.join(dir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) return;
try {
execFileSync('npm', ['install', '--omit=dev'], {
cwd: dir,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
...(isWindows && { shell: true }),
});
} catch (err) {
throw new Error(`npm install failed in ${dir}: ${getErrorMessage(err)}`);
}
}
function finalizePluginRuntime(pluginDir: string): void {
// Symlink host opencli so TS plugins resolve '@jackwener/opencli/registry'
// against the running host, not a stale npm-published version.
linkHostOpencli(pluginDir);
// Transpile .ts → .js via esbuild (production node can't load .ts directly).
transpilePluginTs(pluginDir);
}
/**
* Shared post-install lifecycle for standalone plugins.
*/
function postInstallLifecycle(pluginDir: string): void {
installDependencies(pluginDir);
finalizePluginRuntime(pluginDir);
}
/**
* Monorepo lifecycle: install shared deps once at repo root, then finalize each sub-plugin.
*/
function postInstallMonorepoLifecycle(repoDir: string, pluginDirs: string[]): void {
installDependencies(repoDir);
for (const pluginDir of pluginDirs) {
finalizePluginRuntime(pluginDir);
}
}
function ensureStandalonePluginReady(pluginDir: string): void {
const validation = validatePluginStructure(pluginDir);
if (!validation.valid) {
throw new Error(`Invalid plugin structure:\n- ${validation.errors.join('\n- ')}`);
}
postInstallLifecycle(pluginDir);
}
type LockEntryInput = Omit<LockEntry, 'installedAt'> & Partial<Pick<LockEntry, 'installedAt'>>;
function upsertLockEntry(
lock: Record<string, LockEntry>,
name: string,
entry: LockEntryInput,
): void {
lock[name] = {
...entry,
installedAt: entry.installedAt ?? new Date().toISOString(),
};
}
function publishStandalonePlugin(
stagingDir: string,
targetDir: string,
writeLock: (commitHash: string | undefined) => void,
): void {
runTransaction((tx) => {
tx.track(beginReplaceDir(stagingDir, targetDir));
writeLock(getCommitHash(targetDir));
});
}
interface MonorepoPublishPlugin {
name: string;
subPath: string;
}
function publishMonorepoPlugins(
repoDir: string,
pluginsDir: string,
plugins: MonorepoPublishPlugin[],
publishRepo?: { stagingDir: string; parentDir: string },
writeLock?: (commitHash: string | undefined) => void,
): void {
runTransaction((tx) => {
if (publishRepo) {
fs.mkdirSync(publishRepo.parentDir, { recursive: true });
tx.track(beginReplaceDir(publishRepo.stagingDir, repoDir));
}
const commitHash = getCommitHash(repoDir);
for (const plugin of plugins) {
const linkPath = path.join(pluginsDir, plugin.name);
const subDir = path.join(repoDir, plugin.subPath);
tx.track(beginReplaceSymlink(subDir, linkPath));
}
writeLock?.(commitHash);
});
}
/**
* Install a plugin from a source.
* Supports:
* "github:user/repo" — single plugin or full monorepo
* "github:user/repo/subplugin" — specific sub-plugin from a monorepo
* "https://github.com/user/repo"
* "file:///absolute/path" — local plugin directory (symlinked)
* "/absolute/path" — local plugin directory (symlinked)
*
* Returns the installed plugin name(s).
*/
export function installPlugin(source: string): string | string[] {
const parsed = parseSource(source);
if (!parsed) {
throw new Error(
`Invalid plugin source: "${source}"\n` +
`Supported formats:\n` +
` github:user/repo\n` +
` github:user/repo/subplugin\n` +
` https://github.com/user/repo\n` +
` https://<host>/<path>/repo.git\n` +
` ssh://git@<host>/<path>/repo.git\n` +
` git@<host>:user/repo.git\n` +
` file:///absolute/path\n` +
` /absolute/path`
);
}
const { name: repoName, subPlugin } = parsed;
if (parsed.type === 'local') {
return installLocalPlugin(parsed.localPath!, repoName);
}
return withTempClone(parsed.cloneUrl!, (tmpCloneDir) => {
const manifest = readPluginManifest(tmpCloneDir);
// Check top-level compatibility
if (manifest?.opencli && !checkCompatibility(manifest.opencli)) {
throw new Error(
`Plugin requires opencli ${manifest.opencli}, but current version is incompatible.`
);
}
if (manifest && isMonorepo(manifest)) {
return installMonorepo(tmpCloneDir, parsed.cloneUrl!, repoName, manifest, subPlugin);
}
// Single plugin mode
return installSinglePlugin(tmpCloneDir, parsed.cloneUrl!, repoName, manifest);
});
}
/** Install a single (non-monorepo) plugin. */
function installSinglePlugin(
cloneDir: string,
cloneUrl: string,
name: string,
manifest: PluginManifest | null,
): string {
const pluginName = manifest?.name ?? name;
const targetDir = path.join(PLUGINS_DIR, pluginName);
if (fs.existsSync(targetDir)) {
throw new Error(`Plugin "${pluginName}" is already installed at ${targetDir}`);
}
ensureStandalonePluginReady(cloneDir);
publishStandalonePlugin(cloneDir, targetDir, (commitHash) => {
const lock = readLockFile();
if (commitHash) {
upsertLockEntry(lock, pluginName, {
source: { kind: 'git', url: cloneUrl },
commitHash,
});
writeLockFile(lock);
}
});
return pluginName;
}
/**
* Install a local plugin by creating a symlink.
* Used for plugin development: the source directory is symlinked into
* the plugins dir so changes are reflected immediately.
*/
function installLocalPlugin(localPath: string, name: string): string {
if (!fs.existsSync(localPath)) {
throw new Error(`Local plugin path does not exist: ${localPath}`);
}
const stat = fs.statSync(localPath);
if (!stat.isDirectory()) {
throw new Error(`Local plugin path is not a directory: ${localPath}`);
}
const manifest = readPluginManifest(localPath);
if (manifest?.opencli && !checkCompatibility(manifest.opencli)) {
throw new Error(
`Plugin requires opencli ${manifest.opencli}, but current version is incompatible.`
);
}
const pluginName = manifest?.name ?? name;
const targetDir = path.join(PLUGINS_DIR, pluginName);
if (fs.existsSync(targetDir)) {
throw new Error(`Plugin "${pluginName}" is already installed at ${targetDir}`);
}
const validation = validatePluginStructure(localPath);
if (!validation.valid) {
throw new Error(`Invalid plugin structure:\n- ${validation.errors.join('\n- ')}`);
}
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
const resolvedPath = path.resolve(localPath);
const linkType = isWindows ? 'junction' : 'dir';
fs.symlinkSync(resolvedPath, targetDir, linkType);
installDependencies(localPath);
finalizePluginRuntime(localPath);
const lock = readLockFile();
const commitHash = getCommitHash(localPath);
upsertLockEntry(lock, pluginName, {
source: { kind: 'local', path: resolvedPath },
commitHash: commitHash ?? 'local',
});
writeLockFile(lock);
return pluginName;
}
function updateLocalPlugin(
name: string,
targetDir: string,
lock: Record<string, LockEntry>,
lockEntry?: LockEntry,
): void {
const pluginDir = fs.realpathSync(targetDir);
const validation = validatePluginStructure(pluginDir);
if (!validation.valid) {
log.warn(`Plugin "${name}" structure invalid:\n- ${validation.errors.join('\n- ')}`);
}
postInstallLifecycle(pluginDir);
upsertLockEntry(lock, name, {
source: lockEntry?.source ?? { kind: 'local', path: pluginDir },
commitHash: getCommitHash(pluginDir) ?? 'local',
installedAt: lockEntry?.installedAt ?? new Date().toISOString(),
updatedAt: new Date().toISOString(),
});
writeLockFile(lock);
}
/** Install sub-plugins from a monorepo. */
function installMonorepo(
cloneDir: string,
cloneUrl: string,
repoName: string,
manifest: PluginManifest,
subPlugin?: string,
): string[] {
const monoreposDir = getMonoreposDir();
const repoDir = path.join(monoreposDir, repoName);
const repoAlreadyInstalled = fs.existsSync(repoDir);
const repoRoot = repoAlreadyInstalled ? repoDir : cloneDir;
const effectiveManifest = repoAlreadyInstalled ? readPluginManifest(repoDir) : manifest;
if (!effectiveManifest || !isMonorepo(effectiveManifest)) {
throw new Error(`Monorepo manifest missing or invalid at ${repoRoot}`);
}
let pluginsToInstall = getEnabledPlugins(effectiveManifest);
// If a specific sub-plugin was requested, filter to just that one
if (subPlugin) {
pluginsToInstall = pluginsToInstall.filter((p) => p.name === subPlugin);
if (pluginsToInstall.length === 0) {
// Check if it exists but is disabled
const disabled = effectiveManifest.plugins?.[subPlugin];
if (disabled) {
throw new Error(`Sub-plugin "${subPlugin}" is disabled in the manifest.`);
}
throw new Error(
`Sub-plugin "${subPlugin}" not found in monorepo. Available: ${Object.keys(effectiveManifest.plugins ?? {}).join(', ')}`
);
}
}
const installedNames: string[] = [];
const lock = readLockFile();
const eligiblePlugins: Array<{ name: string; entry: typeof pluginsToInstall[number]['entry'] }> = [];
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
for (const { name, entry } of pluginsToInstall) {
// Check sub-plugin level compatibility (overrides top-level)
if (entry.opencli && !checkCompatibility(entry.opencli)) {
log.warn(`Skipping "${name}": requires opencli ${entry.opencli}`);
continue;
}
const subDir = path.join(repoRoot, entry.path);
if (!fs.existsSync(subDir)) {
log.warn(`Skipping "${name}": path "${entry.path}" not found in repo.`);
continue;
}
const validation = validatePluginStructure(subDir);
if (!validation.valid) {
log.warn(`Skipping "${name}": invalid structure — ${validation.errors.join(', ')}`);
continue;
}
const linkPath = path.join(PLUGINS_DIR, name);
if (fs.existsSync(linkPath)) {
log.warn(`Skipping "${name}": already installed at ${linkPath}`);
continue;
}
eligiblePlugins.push({ name, entry });
}
if (eligiblePlugins.length === 0) {
return installedNames;
}
const publishPlugins = eligiblePlugins.map(({ name, entry }) => ({ name, subPath: entry.path }));
if (repoAlreadyInstalled) {
postInstallMonorepoLifecycle(repoDir, eligiblePlugins.map((p) => path.join(repoDir, p.entry.path)));
} else {
postInstallMonorepoLifecycle(cloneDir, eligiblePlugins.map((p) => path.join(cloneDir, p.entry.path)));
}
publishMonorepoPlugins(
repoDir,
PLUGINS_DIR,
publishPlugins,
repoAlreadyInstalled ? undefined : { stagingDir: cloneDir, parentDir: monoreposDir },
(commitHash) => {
for (const { name, entry } of eligiblePlugins) {
if (commitHash) {
upsertLockEntry(lock, name, {
source: {
kind: 'monorepo',
url: cloneUrl,
repoName,
subPath: entry.path,
},
commitHash,
});
}
installedNames.push(name);
}
writeLockFile(lock);
},
);
return installedNames;
}
function collectUpdatedMonorepoPlugins(
monoName: string,
lock: Record<string, LockEntry>,
manifest: PluginManifest,
cloneUrl: string,
tmpCloneDir: string,
): Array<{
name: string;
lockEntry: LockEntry;
manifestEntry: NonNullable<PluginManifest['plugins']>[string];
}> {
const updatedPlugins: Array<{
name: string;
lockEntry: LockEntry;
manifestEntry: NonNullable<PluginManifest['plugins']>[string];
}> = [];
for (const [pluginName, entry] of Object.entries(lock)) {
if (entry.source.kind !== 'monorepo' || entry.source.repoName !== monoName) continue;
const manifestEntry = manifest.plugins?.[pluginName];
if (!manifestEntry || manifestEntry.disabled) {
throw new Error(`Installed sub-plugin "${pluginName}" no longer exists in ${cloneUrl}`);
}
if (manifestEntry.opencli && !checkCompatibility(manifestEntry.opencli)) {
throw new Error(`Sub-plugin "${pluginName}" requires opencli ${manifestEntry.opencli}`);
}
const subDir = path.join(tmpCloneDir, manifestEntry.path);
const validation = validatePluginStructure(subDir);
if (!validation.valid) {
throw new Error(`Updated sub-plugin "${pluginName}" is invalid:\n- ${validation.errors.join('\n- ')}`);
}
updatedPlugins.push({ name: pluginName, lockEntry: entry, manifestEntry });
}
return updatedPlugins;
}
function updateMonorepoLockEntries(
lock: Record<string, LockEntry>,
plugins: Array<{
name: string;
lockEntry: LockEntry;
manifestEntry: NonNullable<PluginManifest['plugins']>[string];
}>,
cloneUrl: string,
monoName: string,
commitHash: string | undefined,
): void {
for (const plugin of plugins) {
if (!commitHash) continue;
upsertLockEntry(lock, plugin.name, {
...plugin.lockEntry,
source: {
kind: 'monorepo',
url: cloneUrl,
repoName: monoName,
subPath: plugin.manifestEntry.path,
},
commitHash,
updatedAt: new Date().toISOString(),