opencode-rules-md 0.7.0 → 0.8.0

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.
Files changed (47) hide show
  1. package/README.md +13 -3
  2. package/dist/src/active-rules-state.js +1 -1
  3. package/dist/src/active-rules-state.js.map +1 -1
  4. package/dist/src/rule-discovery.d.ts +1 -1
  5. package/dist/src/rule-discovery.d.ts.map +1 -1
  6. package/dist/src/rule-discovery.js +2 -2
  7. package/dist/src/rule-discovery.js.map +1 -1
  8. package/dist/tui/data/rules.d.ts +1 -1
  9. package/dist/tui/data/rules.d.ts.map +1 -1
  10. package/dist/tui/data/rules.js +2 -2
  11. package/dist/tui/data/rules.js.map +1 -1
  12. package/dist/tui/index.js +1 -1
  13. package/dist/tui/index.js.map +1 -1
  14. package/dist/tui/slots/sidebar-content.js +1 -1
  15. package/dist/tui/slots/sidebar-content.js.map +1 -1
  16. package/package.json +7 -11
  17. package/src/active-rules-state.ts +1 -1
  18. package/src/rule-discovery.ts +2 -2
  19. package/tui/data/rules.ts +3 -3
  20. package/tui/index.tsx +1 -1
  21. package/tui/slots/sidebar-content.tsx +1 -1
  22. package/dist/cli.mjs +0 -454
  23. package/dist/src/cli/config.d.ts +0 -74
  24. package/dist/src/cli/config.d.ts.map +0 -1
  25. package/dist/src/cli/config.js +0 -292
  26. package/dist/src/cli/config.js.map +0 -1
  27. package/dist/src/cli/install.d.ts +0 -33
  28. package/dist/src/cli/install.d.ts.map +0 -1
  29. package/dist/src/cli/install.js +0 -99
  30. package/dist/src/cli/install.js.map +0 -1
  31. package/dist/src/cli/main.d.ts +0 -19
  32. package/dist/src/cli/main.d.ts.map +0 -1
  33. package/dist/src/cli/main.js +0 -149
  34. package/dist/src/cli/main.js.map +0 -1
  35. package/dist/src/cli/real-fs.d.ts +0 -26
  36. package/dist/src/cli/real-fs.d.ts.map +0 -1
  37. package/dist/src/cli/real-fs.js +0 -42
  38. package/dist/src/cli/real-fs.js.map +0 -1
  39. package/dist/src/cli/status.d.ts +0 -34
  40. package/dist/src/cli/status.d.ts.map +0 -1
  41. package/dist/src/cli/status.js +0 -67
  42. package/dist/src/cli/status.js.map +0 -1
  43. package/src/cli/config.ts +0 -364
  44. package/src/cli/install.ts +0 -171
  45. package/src/cli/main.ts +0 -178
  46. package/src/cli/real-fs.ts +0 -65
  47. package/src/cli/status.ts +0 -99
@@ -1,42 +0,0 @@
1
- /**
2
- * Thin synchronous adapter over node:fs that implements the CliFs interface.
3
- * All production CLI disk I/O flows through this module — no direct node:fs
4
- * calls outside this file.
5
- */
6
- import * as fs from 'node:fs';
7
- import * as nodePath from 'node:path';
8
- /**
9
- * Production CliFs implementation backed by node:fs (synchronous).
10
- */
11
- export const realFs = {
12
- readFileSync(filePath) {
13
- return fs.readFileSync(filePath, 'utf-8');
14
- },
15
- writeFileSync(filePath, content, _encoding) {
16
- // Ensure parent directory exists before writing
17
- const dir = nodePath.dirname(filePath);
18
- if (!fs.existsSync(dir)) {
19
- fs.mkdirSync(dir, { recursive: true });
20
- }
21
- fs.writeFileSync(filePath, content, 'utf-8');
22
- },
23
- renameSync(from, to) {
24
- fs.renameSync(from, to);
25
- },
26
- copyFileSync(from, to) {
27
- fs.copyFileSync(from, to);
28
- },
29
- unlinkSync(filePath) {
30
- fs.unlinkSync(filePath);
31
- },
32
- mkdirSync(filePath, opts) {
33
- fs.mkdirSync(filePath, opts);
34
- },
35
- readdirSync(filePath) {
36
- return fs.readdirSync(filePath);
37
- },
38
- existsSync(filePath) {
39
- return fs.existsSync(filePath);
40
- },
41
- };
42
- //# sourceMappingURL=real-fs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"real-fs.js","sourceRoot":"","sources":["../../../src/cli/real-fs.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,QAAQ,MAAM,WAAW,CAAC;AAiBtC;;GAEG;AACH,MAAM,CAAC,MAAM,MAAM,GAAU;IAC3B,YAAY,CAAC,QAAgB;QAC3B,OAAO,EAAE,CAAC,YAAY,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5C,CAAC;IAED,aAAa,CAAC,QAAgB,EAAE,OAAe,EAAE,SAAkB;QACjE,gDAAgD;QAChD,MAAM,GAAG,GAAG,QAAQ,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACvC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YACxB,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACzC,CAAC;QACD,EAAE,CAAC,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAC/C,CAAC;IAED,UAAU,CAAC,IAAY,EAAE,EAAU;QACjC,EAAE,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAC1B,CAAC;IAED,YAAY,CAAC,IAAY,EAAE,EAAU;QACnC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IAC5B,CAAC;IAED,UAAU,CAAC,QAAgB;QACzB,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC;IAED,SAAS,CAAC,QAAgB,EAAE,IAA8B;QACxD,EAAE,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IAED,WAAW,CAAC,QAAgB;QAC1B,OAAO,EAAE,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;IAClC,CAAC;IAED,UAAU,CAAC,QAAgB;QACzB,OAAO,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;IACjC,CAAC;CACF,CAAC"}
@@ -1,34 +0,0 @@
1
- /**
2
- * status command: read-only probe that reports install state.
3
- *
4
- * Reports install state across BOTH the server and TUI configs:
5
- * - installed: yes/no (true only when present in both configs)
6
- * - serverSpecifier: the registered entry in opencode.json (or undefined)
7
- * - tuiSpecifier: the registered entry in tui.json (or undefined)
8
- * - serverPath: path to the server config
9
- * - tuiPath: path to the TUI config
10
- * - version: bundled CLI version from package.json
11
- */
12
- import type { CliFs } from './real-fs.js';
13
- export interface StatusResult {
14
- /** True only when the plugin is registered in both server and TUI configs. */
15
- installed: boolean;
16
- /** Server config path. */
17
- serverPath: string;
18
- /** TUI config path. */
19
- tuiPath: string;
20
- /** Registered specifier in the server config, if any. */
21
- serverSpecifier?: string;
22
- /** Registered specifier in the TUI config, if any. */
23
- tuiSpecifier?: string;
24
- /** Whether the server config existed on disk before the probe. */
25
- serverExisted: boolean;
26
- /** Whether the TUI config existed on disk before the probe. */
27
- tuiExisted: boolean;
28
- /** Bundled CLI version from package.json. */
29
- version: string;
30
- /** First parse error encountered, if any (server takes priority). */
31
- parseError?: Error;
32
- }
33
- export declare function runStatus(cliFs?: CliFs): StatusResult;
34
- //# sourceMappingURL=status.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../../../src/cli/status.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAC;AAS1C,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,SAAS,EAAE,OAAO,CAAC;IACnB,0BAA0B;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,uBAAuB;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,yDAAyD;IACzD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,sDAAsD;IACtD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,aAAa,EAAE,OAAO,CAAC;IACvB,+DAA+D;IAC/D,UAAU,EAAE,OAAO,CAAC;IACpB,6CAA6C;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,qEAAqE;IACrE,UAAU,CAAC,EAAE,KAAK,CAAC;CACpB;AAMD,wBAAgB,SAAS,CAAC,KAAK,GAAE,KAAc,GAAG,YAAY,CA0B7D"}
@@ -1,67 +0,0 @@
1
- /**
2
- * status command: read-only probe that reports install state.
3
- *
4
- * Reports install state across BOTH the server and TUI configs:
5
- * - installed: yes/no (true only when present in both configs)
6
- * - serverSpecifier: the registered entry in opencode.json (or undefined)
7
- * - tuiSpecifier: the registered entry in tui.json (or undefined)
8
- * - serverPath: path to the server config
9
- * - tuiPath: path to the TUI config
10
- * - version: bundled CLI version from package.json
11
- */
12
- import { loadGlobalConfig, TUI_CONFIG_FILENAME } from './config.js';
13
- import { realFs } from './real-fs.js';
14
- import * as fs from 'node:fs';
15
- import * as path from 'node:path';
16
- // ---------------------------------------------------------------------------
17
- // Run status
18
- // ---------------------------------------------------------------------------
19
- export function runStatus(cliFs = realFs) {
20
- const serverLoad = loadGlobalConfig(cliFs);
21
- const tuiLoad = loadGlobalConfig(cliFs, { filename: TUI_CONFIG_FILENAME });
22
- const serverSpecifier = findSpecifier(serverLoad);
23
- const tuiSpecifier = findSpecifier(tuiLoad);
24
- const installed = serverSpecifier !== undefined && tuiSpecifier !== undefined;
25
- const result = {
26
- installed,
27
- serverPath: serverLoad.path,
28
- tuiPath: tuiLoad.path,
29
- serverExisted: serverLoad.existed,
30
- tuiExisted: tuiLoad.existed,
31
- version: getVersion(),
32
- };
33
- if (serverSpecifier)
34
- result.serverSpecifier = serverSpecifier;
35
- if (tuiSpecifier)
36
- result.tuiSpecifier = tuiSpecifier;
37
- // Surface the first parse error so callers can warn the user
38
- const parseError = serverLoad.parseError ?? tuiLoad.parseError;
39
- if (parseError)
40
- result.parseError = parseError;
41
- return result;
42
- }
43
- // ---------------------------------------------------------------------------
44
- // Internal helpers
45
- // ---------------------------------------------------------------------------
46
- function findSpecifier(load) {
47
- if (load.parseError)
48
- return undefined;
49
- const config = load.config;
50
- const pluginList = Array.isArray(config['plugin'])
51
- ? config['plugin']
52
- : [];
53
- return pluginList.find(p => p.startsWith('opencode-rules-md'));
54
- }
55
- function getVersion() {
56
- try {
57
- // Read package.json relative to the project root
58
- const pkgPath = path.resolve(process.cwd(), 'package.json');
59
- const content = fs.readFileSync(pkgPath, 'utf-8');
60
- const pkg = JSON.parse(content);
61
- return pkg.version ?? 'unknown';
62
- }
63
- catch {
64
- return 'unknown';
65
- }
66
- }
67
- //# sourceMappingURL=status.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"status.js","sourceRoot":"","sources":["../../../src/cli/status.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEpE,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AA2BlC,8EAA8E;AAC9E,aAAa;AACb,8EAA8E;AAE9E,MAAM,UAAU,SAAS,CAAC,QAAe,MAAM;IAC7C,MAAM,UAAU,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAC3C,MAAM,OAAO,GAAG,gBAAgB,CAAC,KAAK,EAAE,EAAE,QAAQ,EAAE,mBAAmB,EAAE,CAAC,CAAC;IAE3E,MAAM,eAAe,GAAG,aAAa,CAAC,UAAU,CAAC,CAAC;IAClD,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IAE5C,MAAM,SAAS,GAAG,eAAe,KAAK,SAAS,IAAI,YAAY,KAAK,SAAS,CAAC;IAE9E,MAAM,MAAM,GAAiB;QAC3B,SAAS;QACT,UAAU,EAAE,UAAU,CAAC,IAAI;QAC3B,OAAO,EAAE,OAAO,CAAC,IAAI;QACrB,aAAa,EAAE,UAAU,CAAC,OAAO;QACjC,UAAU,EAAE,OAAO,CAAC,OAAO;QAC3B,OAAO,EAAE,UAAU,EAAE;KACtB,CAAC;IAEF,IAAI,eAAe;QAAE,MAAM,CAAC,eAAe,GAAG,eAAe,CAAC;IAC9D,IAAI,YAAY;QAAE,MAAM,CAAC,YAAY,GAAG,YAAY,CAAC;IAErD,6DAA6D;IAC7D,MAAM,UAAU,GAAG,UAAU,CAAC,UAAU,IAAI,OAAO,CAAC,UAAU,CAAC;IAC/D,IAAI,UAAU;QAAE,MAAM,CAAC,UAAU,GAAG,UAAU,CAAC;IAE/C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,8EAA8E;AAC9E,mBAAmB;AACnB,8EAA8E;AAE9E,SAAS,aAAa,CAAC,IAAyC;IAC9D,IAAI,IAAI,CAAC,UAAU;QAAE,OAAO,SAAS,CAAC;IACtC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IAC3B,MAAM,UAAU,GAAa,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC1D,CAAC,CAAE,MAAM,CAAC,QAAQ,CAAc;QAChC,CAAC,CAAC,EAAE,CAAC;IACP,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC,CAAC;AACjE,CAAC;AAED,SAAS,UAAU;IACjB,IAAI,CAAC;QACH,iDAAiD;QACjD,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,cAAc,CAAC,CAAC;QAC5D,MAAM,OAAO,GAAG,EAAE,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAClD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAyB,CAAC;QACxD,OAAO,GAAG,CAAC,OAAO,IAAI,SAAS,CAAC;IAClC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC"}
package/src/cli/config.ts DELETED
@@ -1,364 +0,0 @@
1
- /**
2
- * CLI config helpers: discovery, JSONC-safe parsing, plugin normalization,
3
- * backup rotation, and atomic write.
4
- *
5
- * All filesystem access goes through the CliFs interface so tests can inject
6
- * an in-memory implementation without touching real disk.
7
- */
8
-
9
- import * as os from 'node:os';
10
- import * as path from 'node:path';
11
- import type { CliFs } from './real-fs.js';
12
-
13
- // ---------------------------------------------------------------------------
14
- // Public constants
15
- // ---------------------------------------------------------------------------
16
-
17
- /** npm package name for this plugin. */
18
- export const PLUGIN_NAME = 'opencode-rules-md';
19
-
20
- /** Filename for the OpenCode server config. */
21
- export const SERVER_CONFIG_FILENAME = 'opencode.json';
22
-
23
- /** Filename for the OpenCode TUI config. */
24
- export const TUI_CONFIG_FILENAME = 'tui.json';
25
-
26
- // ---------------------------------------------------------------------------
27
- // Public types
28
- // ---------------------------------------------------------------------------
29
-
30
- export interface LoadResult {
31
- path: string;
32
- existed: boolean;
33
- config: Record<string, unknown>;
34
- parseError?: Error;
35
- }
36
-
37
- // ---------------------------------------------------------------------------
38
- // JSONC comment stripper — two-pass
39
- // ---------------------------------------------------------------------------
40
-
41
- /**
42
- * Strip JSONC comments and trailing commas while preserving
43
- * comment-like sequences inside string literals.
44
- *
45
- * Pass 1: strip `//` and `/* * /` comments (string-aware).
46
- * Pass 2: strip trailing commas before `}` or `]`, skipping whitespace.
47
- */
48
- export function stripJsoncComments(content: string): string {
49
- // Pass 1 — strip comments while preserving string contents
50
- let result = '';
51
- let i = 0;
52
- let inString = false;
53
- let escaped = false;
54
- const len = content.length;
55
-
56
- while (i < len) {
57
- const char = content[i]!;
58
-
59
- if (inString) {
60
- result += char;
61
- if (escaped) {
62
- escaped = false;
63
- } else if (char === '\\') {
64
- escaped = true;
65
- } else if (char === '"') {
66
- inString = false;
67
- }
68
- i++;
69
- continue;
70
- }
71
-
72
- if (char === '"') {
73
- inString = true;
74
- result += char;
75
- i++;
76
- continue;
77
- }
78
-
79
- // Line comment: // until newline
80
- if (char === '/' && content[i + 1] === '/') {
81
- i += 2;
82
- while (i < len && content[i] !== '\n') i++;
83
- continue;
84
- }
85
-
86
- // Block comment: /* until */
87
- if (char === '/' && content[i + 1] === '*') {
88
- i += 2;
89
- while (i < len && !(content[i] === '*' && content[i + 1] === '/')) i++;
90
- if (i < len) i += 2; // skip past */
91
- continue;
92
- }
93
-
94
- result += char;
95
- i++;
96
- }
97
-
98
- // Pass 2 — strip trailing commas (with whitespace skip) before } or ]
99
- let out = '';
100
- let inStr = false;
101
- let esc = false;
102
- let j = 0;
103
- const outLen = result.length;
104
-
105
- while (j < outLen) {
106
- const ch = result[j]!;
107
-
108
- if (inStr) {
109
- out += ch;
110
- if (esc) {
111
- esc = false;
112
- } else if (ch === '\\') {
113
- esc = true;
114
- } else if (ch === '"') {
115
- inStr = false;
116
- }
117
- j++;
118
- continue;
119
- }
120
-
121
- if (ch === '"') {
122
- inStr = true;
123
- out += ch;
124
- j++;
125
- continue;
126
- }
127
-
128
- if (ch === ',') {
129
- // Skip whitespace before checking for } or ]
130
- let k = j + 1;
131
- while (k < outLen && /\s/.test(result[k]!)) k++;
132
- if (k < outLen && /[}\]]/.test(result[k]!)) {
133
- // Drop the comma; jump to the bracket
134
- j = k;
135
- continue;
136
- }
137
- }
138
-
139
- out += ch;
140
- j++;
141
- }
142
-
143
- return out;
144
- }
145
-
146
- // ---------------------------------------------------------------------------
147
- // Config path resolution
148
- // ---------------------------------------------------------------------------
149
-
150
- /**
151
- * Resolve the global opencode config path using the same precedence as
152
- * opencode itself: OPENCODE_CONFIG_DIR → XDG_CONFIG_HOME → HOME fallback.
153
- *
154
- * On Windows, APPDATA is tried as a last resort when XDG_CONFIG_HOME and
155
- * HOME are both absent.
156
- */
157
- export function resolveGlobalConfigPath(
158
- fs: CliFs,
159
- opts: { ensureDir?: boolean; filename?: string } = {}
160
- ): string {
161
- const dir = resolveConfigDir();
162
- if (opts.ensureDir && !fs.existsSync(dir)) {
163
- fs.mkdirSync(dir, { recursive: true });
164
- }
165
- const filename = opts.filename ?? SERVER_CONFIG_FILENAME;
166
- return path.join(dir, filename);
167
- }
168
-
169
- function resolveConfigDir(): string {
170
- if (process.env.OPENCODE_CONFIG_DIR) {
171
- return process.env.OPENCODE_CONFIG_DIR;
172
- }
173
-
174
- if (process.env.XDG_CONFIG_HOME) {
175
- return path.join(process.env.XDG_CONFIG_HOME, 'opencode');
176
- }
177
-
178
- const home = process.env.HOME || os.homedir();
179
- if (home) {
180
- return path.join(home, '.config', 'opencode');
181
- }
182
-
183
- // Windows fallback
184
- const appdata = process.env.APPDATA;
185
- if (appdata) {
186
- return path.join(appdata, 'opencode');
187
- }
188
-
189
- throw new Error(
190
- 'Cannot resolve config dir: none of OPENCODE_CONFIG_DIR, XDG_CONFIG_HOME, HOME, or APPDATA is set'
191
- );
192
- }
193
-
194
- // ---------------------------------------------------------------------------
195
- // JSONC-safe config load
196
- // ---------------------------------------------------------------------------
197
-
198
- /**
199
- * Load and parse a global OpenCode config file.
200
- * Treats a missing file as an empty config object (not an error).
201
- * Surfaces parse errors so callers can exit non-zero without corrupting data.
202
- */
203
- export function loadGlobalConfig(fs: CliFs, opts: { filename?: string } = {}): LoadResult {
204
- const configPath = resolveGlobalConfigPath(
205
- fs,
206
- opts.filename ? { filename: opts.filename } : {}
207
- );
208
-
209
- if (!fs.existsSync(configPath)) {
210
- return { path: configPath, existed: false, config: {} };
211
- }
212
-
213
- try {
214
- const raw = fs.readFileSync(configPath);
215
- const stripped = stripJsoncComments(raw);
216
- // Empty after stripping means comment-only file — treat as {}
217
- if (stripped.trim() === '') {
218
- return { path: configPath, existed: true, config: {} };
219
- }
220
- const parsed = JSON.parse(stripped) as Record<string, unknown>;
221
- return { path: configPath, existed: true, config: parsed };
222
- } catch (err) {
223
- const error = err instanceof Error ? err : new Error(String(err));
224
- return { path: configPath, existed: true, config: {}, parseError: error };
225
- }
226
- }
227
-
228
- // ---------------------------------------------------------------------------
229
- // Plugin normalization helpers
230
- // ---------------------------------------------------------------------------
231
-
232
- /**
233
- * Return the plugin array with opencode-rules-md* entries deduplicated by
234
- * name prefix, keeping the last occurrence of each unique prefix.
235
- */
236
- export function normalizePlugin(
237
- config: Record<string, unknown>
238
- ): string[] {
239
- const raw: unknown[] = Array.isArray(config['plugin']) ? config['plugin'] : [];
240
- const seen = new Map<string, number>(); // prefix → last index
241
- const result: string[] = [];
242
-
243
- for (const item of raw) {
244
- if (typeof item !== 'string') continue;
245
- const prefix = getPluginPrefix(item);
246
- seen.set(prefix, result.length);
247
- result.push(item);
248
- }
249
-
250
- // Collapse entries sharing a prefix to only the last one
251
- return collapseByPrefix(result, seen);
252
- }
253
-
254
- /**
255
- * Remove all plugins matching the given prefix (used to dedupe before append).
256
- */
257
- export function removePlugin(
258
- config: Record<string, unknown>,
259
- prefix: string
260
- ): void {
261
- if (!Array.isArray(config['plugin'])) return;
262
- const raw = config['plugin'] as string[];
263
- config['plugin'] = raw.filter(
264
- item => typeof item === 'string' && !item.startsWith(prefix)
265
- );
266
- }
267
-
268
- /**
269
- * Add a plugin specifier, removing any existing entry with the same prefix first
270
- * so it ends up at the specified position (default: end). This makes the operation
271
- * idempotent — re-adding the same specifier just moves it to the end.
272
- */
273
- export function addPlugin(
274
- config: Record<string, unknown>,
275
- specifier: string
276
- ): void {
277
- if (!Array.isArray(config['plugin'])) {
278
- config['plugin'] = [];
279
- }
280
- const plugin = config['plugin'] as string[];
281
- const prefix = getPluginPrefix(specifier);
282
- // Remove any existing entry with the same prefix
283
- const removed = plugin.filter(p => getPluginPrefix(p) !== prefix);
284
- removed.push(specifier);
285
- config['plugin'] = removed;
286
- }
287
-
288
- // ---------------------------------------------------------------------------
289
- // Backup rotation
290
- // ---------------------------------------------------------------------------
291
-
292
- /**
293
- * Write a timestamped backup of the given config path and rotate so at most
294
- * 3 backups are retained (oldest deleted first).
295
- * Returns the path of the newly created backup, or null if no backup was created.
296
- */
297
- export function rotateBackups(fs: CliFs, configPath: string, _pluginName: string): string | null {
298
- if (!fs.existsSync(configPath)) {
299
- return null;
300
- }
301
-
302
- const dir = path.dirname(configPath);
303
- const base = path.basename(configPath);
304
- const timestamp = Date.now();
305
- const newBak = path.join(dir, `${base}.bak.${timestamp}`);
306
-
307
- fs.copyFileSync(configPath, newBak);
308
-
309
- // Collect existing backups sorted by timestamp (lexical sort on numeric suffix)
310
- const entries = fs.readdirSync(dir);
311
- const bakFiles = entries
312
- .filter(e => e.startsWith(base + '.bak.'))
313
- .sort();
314
-
315
- // Remove oldest until only 3 remain
316
- while (bakFiles.length > 3) {
317
- const oldest = bakFiles.shift()!;
318
- fs.unlinkSync(path.join(dir, oldest));
319
- }
320
-
321
- return newBak;
322
- }
323
-
324
- // ---------------------------------------------------------------------------
325
- // Atomic write
326
- // ---------------------------------------------------------------------------
327
-
328
- /**
329
- * Write content to a temporary sibling file then rename it into place.
330
- * The final path is never in a partially-written state.
331
- */
332
- export function writeAtomically(fs: CliFs, configPath: string, content: string): void {
333
- const dir = path.dirname(configPath);
334
- const base = path.basename(configPath);
335
- const tmpPath = path.join(dir, `.${base}.tmp.${Date.now()}-${process.pid}`);
336
-
337
- fs.writeFileSync(tmpPath, content, 'utf-8');
338
- fs.renameSync(tmpPath, configPath);
339
- }
340
-
341
- // ---------------------------------------------------------------------------
342
- // Internal helpers
343
- // ---------------------------------------------------------------------------
344
-
345
- /**
346
- * Extract the name part of a plugin specifier, stripping any version suffix.
347
- * e.g. "opencode-rules-md@0.1.0" → "opencode-rules-md"
348
- */
349
- function getPluginPrefix(specifier: string): string {
350
- const atIdx = specifier.indexOf('@');
351
- return atIdx === -1 ? specifier : specifier.substring(0, atIdx);
352
- }
353
-
354
- /**
355
- * Collapse plugins by prefix, keeping only the last occurrence of each.
356
- */
357
- function collapseByPrefix(
358
- plugins: string[],
359
- lastSeen: Map<string, number>
360
- ): string[] {
361
- const keptIndices = new Set([...lastSeen.values()]);
362
-
363
- return plugins.filter((_, idx) => keptIndices.has(idx));
364
- }
@@ -1,171 +0,0 @@
1
- /**
2
- * install command: idempotently append opencode-rules-md to the global configs.
3
- *
4
- * Registers the plugin in BOTH:
5
- * - Server config: ~/.config/opencode/opencode.json
6
- * - TUI config: ~/.config/opencode/tui.json
7
- *
8
- * Pipeline (per config):
9
- * loadGlobalConfig → abort if parseError (throw) → normalizePlugin
10
- * → check no-op → (dry-run? print & return "planned")
11
- * → rotateBackups → writeAtomically → print & return "wrote"
12
- *
13
- * Errors are surfaced as exceptions instead of silent status returns so
14
- * the CLI dispatcher can print them.
15
- */
16
-
17
- import {
18
- loadGlobalConfig,
19
- normalizePlugin,
20
- removePlugin,
21
- addPlugin,
22
- rotateBackups,
23
- writeAtomically,
24
- TUI_CONFIG_FILENAME,
25
- } from './config.js';
26
- import type { CliFs } from './real-fs.js';
27
- import { realFs } from './real-fs.js';
28
-
29
- // ---------------------------------------------------------------------------
30
- // Result types
31
- // ---------------------------------------------------------------------------
32
-
33
- export interface ConfigUpdateResult {
34
- status: 'wrote' | 'planned' | 'noop';
35
- path: string;
36
- specifier: string;
37
- backup?: string;
38
- }
39
-
40
- export interface InstallResult {
41
- status: 'wrote' | 'planned' | 'noop';
42
- specifier: string;
43
- server: ConfigUpdateResult;
44
- tui: ConfigUpdateResult;
45
- }
46
-
47
- // ---------------------------------------------------------------------------
48
- // Run install
49
- // ---------------------------------------------------------------------------
50
-
51
- export function runInstall(
52
- opts: { version?: string; dryRun?: boolean },
53
- fs: CliFs = realFs
54
- ): InstallResult {
55
- const specifier = buildSpecifier(opts.version);
56
-
57
- const server = updateConfig(specifier, opts.dryRun ?? false, fs);
58
- const tui = updateConfig(specifier, opts.dryRun ?? false, fs, {
59
- filename: TUI_CONFIG_FILENAME,
60
- });
61
-
62
- const aggregate: InstallResult['status'] =
63
- server.status === 'wrote' || tui.status === 'wrote'
64
- ? 'wrote'
65
- : server.status === 'planned' || tui.status === 'planned'
66
- ? 'planned'
67
- : 'noop';
68
-
69
- printSummary(aggregate, specifier, server, tui);
70
-
71
- return { status: aggregate, specifier, server, tui };
72
- }
73
-
74
- // ---------------------------------------------------------------------------
75
- // Internal: update a single config file
76
- // ---------------------------------------------------------------------------
77
-
78
- interface UpdateOpts {
79
- filename?: string;
80
- }
81
-
82
- function updateConfig(
83
- specifier: string,
84
- dryRun: boolean,
85
- fs: CliFs,
86
- opts: UpdateOpts = {}
87
- ): ConfigUpdateResult {
88
- const loadResult = loadGlobalConfig(
89
- fs,
90
- opts.filename ? { filename: opts.filename } : {}
91
- );
92
-
93
- // Throw on parse error — better to fail fast than to silently corrupt config
94
- if (loadResult.parseError) {
95
- const filename = opts.filename ?? 'opencode.json';
96
- const err: Error & { configPath?: string } = new Error(
97
- `opencode-rules-md: ${filename} is malformed — aborting to avoid data loss.\n` +
98
- ` path: ${loadResult.path}\n` +
99
- ` error: ${loadResult.parseError.message}`
100
- );
101
- err.configPath = loadResult.path;
102
- throw err;
103
- }
104
-
105
- const configPath = loadResult.path;
106
- const config = loadResult.config;
107
-
108
- // Normalize plugin array (dedupe by prefix)
109
- config['plugin'] = normalizePlugin(config);
110
-
111
- // Check if already installed with the same specifier — no-op
112
- const existing = (config['plugin'] as string[] | undefined) ?? [];
113
- if (existing.includes(specifier)) {
114
- return { status: 'noop', path: configPath, specifier };
115
- }
116
-
117
- // Remove any existing opencode-rules-md* entries so this specifier is deduplicated
118
- removePlugin(config, 'opencode-rules-md');
119
-
120
- // Add the new (or re-added) specifier at the end
121
- addPlugin(config, specifier);
122
-
123
- // Dry-run: serialize and print planned content, make no changes
124
- if (dryRun) {
125
- const planned = JSON.stringify(config, null, 2);
126
- console.log(`Planned ${configPath}:\n${planned}`);
127
- return { status: 'planned', path: configPath, specifier };
128
- }
129
-
130
- // Write: rotate backups first, then atomic write
131
- const backup = rotateBackups(fs, configPath, 'opencode-rules-md');
132
- const serialized = JSON.stringify(config, null, 2);
133
- writeAtomically(fs, configPath, serialized);
134
-
135
- const result: ConfigUpdateResult = { status: 'wrote', path: configPath, specifier };
136
- if (backup) result.backup = backup;
137
- return result;
138
- }
139
-
140
- // ---------------------------------------------------------------------------
141
- // Internal helpers
142
- // ---------------------------------------------------------------------------
143
-
144
- function buildSpecifier(version?: string): string {
145
- return version ? `opencode-rules-md@${version}` : 'opencode-rules-md';
146
- }
147
-
148
- function printSummary(
149
- status: InstallResult['status'],
150
- specifier: string,
151
- server: ConfigUpdateResult,
152
- tui: ConfigUpdateResult
153
- ): void {
154
- if (status === 'noop') {
155
- console.log(`Already installed (${specifier})`);
156
- console.log(` server config: ${server.path}`);
157
- console.log(` tui config: ${tui.path}`);
158
- return;
159
- }
160
-
161
- if (status === 'planned') {
162
- console.log('Dry run complete — no files written.');
163
- return;
164
- }
165
-
166
- console.log(`Installed ${specifier}`);
167
- console.log(` server config: ${server.path}`);
168
- if (server.backup) console.log(` backup: ${server.backup}`);
169
- console.log(` tui config: ${tui.path}`);
170
- if (tui.backup) console.log(` backup: ${tui.backup}`);
171
- }