@xyd-js/opencli 0.0.0-build-b7bd05c-20260701151111

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.
@@ -0,0 +1,218 @@
1
+ import type { OpencliSpecJson, Command } from './types.js';
2
+
3
+ export type IndentStyle = 'code' | 'list';
4
+
5
+ /**
6
+ * Generate usage line for a command (like: "shadcn init [options] [components...]")
7
+ */
8
+ export function generateUsage(
9
+ _spec: OpencliSpecJson,
10
+ command: Command,
11
+ commandPath: string,
12
+ opts: { commandPlaceholder?: boolean } = {},
13
+ ): string {
14
+ const parts: string[] = [];
15
+
16
+ // Command path
17
+ parts.push(commandPath);
18
+
19
+ // A command that owns subcommands takes one as its next token. Opt-in, so
20
+ // consumers that render a command's own usage (e.g. opencli-remark) keep their
21
+ // output — only api.cli asks for the placeholder.
22
+ if (opts.commandPlaceholder && command.commands && command.commands.filter((c) => !c.hidden).length > 0) {
23
+ parts.push('<command>');
24
+ }
25
+
26
+ // Options indicator
27
+ if (command.options && command.options.length > 0) {
28
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
29
+ if (visibleOptions.length > 0) {
30
+ parts.push('[options]');
31
+ }
32
+ }
33
+
34
+ // Arguments
35
+ if (command.arguments && command.arguments.length > 0) {
36
+ const visibleArgs = command.arguments.filter((arg) => !arg.hidden);
37
+ const argParts = visibleArgs.map((arg) => {
38
+ const name = arg.name.toLowerCase();
39
+ // Use ... suffix if argument can accept multiple values (variadic)
40
+ const suffix = arg.variadic ? '...' : '';
41
+ return arg.required ? `<${name}${suffix}>` : `[${name}${suffix}]`;
42
+ });
43
+ parts.push(...argParts);
44
+ }
45
+
46
+ return parts.join(' ');
47
+ }
48
+
49
+ /**
50
+ * Generate description for a command
51
+ */
52
+ export function generateDescription(command: Command): string {
53
+ return command.description || '';
54
+ }
55
+
56
+ /**
57
+ * Generate arguments documentation
58
+ * @param indentStyle - 'code' for tab-indented CLI style, 'list' for markdown list style
59
+ */
60
+ export function generateArguments(command: Command, indentStyle: IndentStyle = 'code'): string {
61
+ if (!command.arguments || command.arguments.length === 0) {
62
+ return '';
63
+ }
64
+
65
+ const visibleArgs = command.arguments.filter((arg) => !arg.hidden);
66
+ if (visibleArgs.length === 0) {
67
+ return '';
68
+ }
69
+
70
+ const lines: string[] = [];
71
+
72
+ for (const arg of visibleArgs) {
73
+ const name = arg.name.toLowerCase();
74
+ const desc = arg.description || '';
75
+
76
+ if (indentStyle === 'list') {
77
+ // Markdown list format: - `package` Package name
78
+ lines.push(`- \`${name}\`${desc ? ` ${desc}` : ''}`);
79
+ } else {
80
+ // Code/CLI format with tab indentation
81
+ const paddedName = name.padEnd(30);
82
+ lines.push(`\t${paddedName}${desc}`);
83
+ }
84
+ }
85
+
86
+ return lines.join('\n');
87
+ }
88
+
89
+ /**
90
+ * Generate options documentation
91
+ * @param indentStyle - 'code' for tab-indented CLI style, 'list' for markdown list style
92
+ */
93
+ export function generateOptions(command: Command, indentStyle: IndentStyle = 'code'): string {
94
+ if (!command.options || command.options.length === 0) {
95
+ return '';
96
+ }
97
+
98
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
99
+ if (visibleOptions.length === 0) {
100
+ return '';
101
+ }
102
+
103
+ const lines: string[] = [];
104
+
105
+ for (const option of visibleOptions) {
106
+ // Build option signature
107
+ const aliases = option.aliases?.filter((a) => a.length === 1) || [];
108
+ const short = aliases.length > 0 ? `-${aliases[0]}` : '';
109
+ const long = `--${option.name}`;
110
+
111
+ // Add argument placeholder if option takes arguments
112
+ let argPlaceholder = '';
113
+ if (option.arguments && option.arguments.length > 0) {
114
+ const argNames = option.arguments.filter((arg) => !arg.hidden).map((arg) => `<${arg.name.toLowerCase()}>`);
115
+ argPlaceholder = ' ' + argNames.join(' ');
116
+ }
117
+
118
+ const desc = option.description || '';
119
+
120
+ if (indentStyle === 'list') {
121
+ // Markdown list format: - `-g`, `--global` Install globally
122
+ const shortPart = short ? `\`${short}\`, ` : '';
123
+ lines.push(`- ${shortPart}\`${long}\`${argPlaceholder}${desc ? ` ${desc}` : ''}`);
124
+ } else {
125
+ // Code/CLI format with tab indentation
126
+ const signature = `${short ? `${short}, ` : ''}${long}${argPlaceholder}`;
127
+ const paddedSignature = signature.padEnd(30);
128
+ lines.push(`\t${paddedSignature}${desc}`);
129
+ }
130
+ }
131
+
132
+ return lines.join('\n');
133
+ }
134
+
135
+ /**
136
+ * TODO: OPTIONS DO ALMOST THE SAME
137
+ * Generate flags/options documentation
138
+ */
139
+ export function generateFlags(command: Command): string {
140
+ if (!command.options || command.options.length === 0) {
141
+ return 'No flags available.';
142
+ }
143
+
144
+ const visibleOptions = command.options.filter((opt) => !opt.hidden);
145
+ if (visibleOptions.length === 0) {
146
+ return 'No flags available.';
147
+ }
148
+
149
+ const lines: string[] = [];
150
+
151
+ for (const option of visibleOptions) {
152
+ const optionParts: string[] = [];
153
+
154
+ // Option name and aliases
155
+ const aliases = option.aliases?.filter((a) => a.length === 1) || [];
156
+ const short = aliases.length > 0 ? `-${aliases[0]}` : '';
157
+ const long = `--${option.name}`;
158
+ const name = short ? `\`${short}\`, \`${long}\`` : `\`${long}\``;
159
+ optionParts.push(name);
160
+
161
+ // Required indicator
162
+ if (option.required) {
163
+ optionParts.push('**(required)**');
164
+ }
165
+
166
+ lines.push(`- ${optionParts.join(' ')}`);
167
+
168
+ // Description
169
+ if (option.description) {
170
+ lines.push(` ${option.description}`);
171
+ }
172
+
173
+ // Option arguments
174
+ if (option.arguments && option.arguments.length > 0) {
175
+ const argParts = option.arguments
176
+ .filter((arg) => !arg.hidden)
177
+ .map((arg) => {
178
+ const name = arg.name.toUpperCase();
179
+ return arg.required ? `<${name}>` : `[${name}]`;
180
+ });
181
+ if (argParts.length > 0) {
182
+ lines.push(` Arguments: ${argParts.join(' ')}`);
183
+ }
184
+ }
185
+ }
186
+
187
+ return lines.join('\n');
188
+ }
189
+
190
+ /**
191
+ * Generate subcommands documentation
192
+ */
193
+ export function generateCommands(command: Command): string {
194
+ if (!command.commands || command.commands.length === 0) {
195
+ return 'No subcommands available.';
196
+ }
197
+
198
+ const visibleCommands = command.commands.filter((cmd) => !cmd.hidden);
199
+ if (visibleCommands.length === 0) {
200
+ return 'No subcommands available.';
201
+ }
202
+
203
+ const lines: string[] = [];
204
+
205
+ for (const subcommand of visibleCommands) {
206
+ lines.push(`- \`${subcommand.name}\``);
207
+
208
+ if (subcommand.aliases && subcommand.aliases.length > 0) {
209
+ lines.push(` Aliases: ${subcommand.aliases.map((a) => `\`${a}\``).join(', ')}`);
210
+ }
211
+
212
+ if (subcommand.description) {
213
+ lines.push(` ${subcommand.description}`);
214
+ }
215
+ }
216
+
217
+ return lines.join('\n');
218
+ }
package/src/index.ts ADDED
@@ -0,0 +1,20 @@
1
+ // OpenCLI core: the data model (generated from opencli-spec.json) plus the
2
+ // pure spec/loader/generator helpers shared by opencli-remark and the
3
+ // openapi2opencli / opencli2* code generators.
4
+ export * from './types';
5
+
6
+ export { loadOpencliSpec, findCommand } from './spec';
7
+ export type { LoadOpencliSpecOptions } from './spec';
8
+
9
+ export {
10
+ generateUsage,
11
+ generateDescription,
12
+ generateArguments,
13
+ generateOptions,
14
+ generateCommands,
15
+ generateFlags,
16
+ } from './generate';
17
+ export type { IndentStyle } from './generate';
18
+
19
+ export { opencliToReferences } from './converters';
20
+ export type { OpencliReference, OpencliToReferencesOptions } from './converters';
package/src/spec.ts ADDED
@@ -0,0 +1,106 @@
1
+ import type { OpencliSpecJson, Command } from './types.js';
2
+
3
+ export interface LoadOpencliSpecOptions {
4
+ /**
5
+ * Base directory used to resolve a relative file `source`.
6
+ * Defaults to `process.cwd()`. (The remark plugin passes the markdown file's dirname.)
7
+ */
8
+ cwd?: string;
9
+ }
10
+
11
+ /**
12
+ * Load an OpenCLI spec from a file path or an HTTP(S) URL.
13
+ *
14
+ * Returns `null` (and logs) on any failure so callers can leave placeholders
15
+ * untouched rather than throwing.
16
+ */
17
+ export async function loadOpencliSpec(
18
+ source: string,
19
+ opts?: LoadOpencliSpecOptions,
20
+ ): Promise<OpencliSpecJson | null> {
21
+ try {
22
+ let content: string;
23
+
24
+ if (source.startsWith('http://') || source.startsWith('https://')) {
25
+ // Load from URL
26
+ const response = await fetch(source);
27
+ if (!response.ok) {
28
+ throw new Error(`Failed to fetch OpenCLI spec: ${response.statusText}`);
29
+ }
30
+ content = await response.text();
31
+ } else {
32
+ // Load from file
33
+ const fs = await import('node:fs/promises');
34
+ const path = await import('node:path');
35
+
36
+ // Resolve relative to the provided cwd (or process.cwd())
37
+ const base = opts?.cwd ?? process.cwd();
38
+ const resolvedPath = path.isAbsolute(source) ? source : path.resolve(base, source);
39
+
40
+ content = await fs.readFile(resolvedPath, 'utf-8');
41
+ }
42
+
43
+ return JSON.parse(content) as OpencliSpecJson;
44
+ } catch (error) {
45
+ console.error(`Error loading OpenCLI spec from ${source}:`, error);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Find a command in the spec by path (e.g., "spice install").
52
+ * If the path is empty, returns a synthetic root command built from the spec root.
53
+ */
54
+ export function findCommand(spec: OpencliSpecJson, commandPath: string): Command | null {
55
+ let parts = commandPath.trim().split(/\s+/).filter(Boolean);
56
+
57
+ // If no path specified, create a synthetic root command from spec root
58
+ if (parts.length === 0) {
59
+ return {
60
+ name: spec.info?.title || 'root',
61
+ description: spec.info?.description || spec.info?.summary,
62
+ options: spec.options || [],
63
+ arguments: spec.arguments || [],
64
+ commands: spec.commands || [],
65
+ examples: spec.examples || [],
66
+ exitCodes: spec.exitCodes || [],
67
+ interactive: spec.interactive,
68
+ };
69
+ }
70
+
71
+ // Skip the CLI name if it matches the first part (e.g., "spice install" -> "install")
72
+ if (parts.length > 0 && spec.info?.title && parts[0] === spec.info.title) {
73
+ parts = parts.slice(1);
74
+ }
75
+
76
+ // If only the CLI name was provided, return root command
77
+ if (parts.length === 0) {
78
+ return {
79
+ name: spec.info?.title || 'root',
80
+ description: spec.info?.description || spec.info?.summary,
81
+ options: spec.options || [],
82
+ arguments: spec.arguments || [],
83
+ commands: spec.commands || [],
84
+ examples: spec.examples || [],
85
+ exitCodes: spec.exitCodes || [],
86
+ interactive: spec.interactive,
87
+ };
88
+ }
89
+
90
+ // Start from root commands
91
+ let currentCommands = spec.commands || [];
92
+ let foundCommand: Command | null = null;
93
+
94
+ for (const part of parts) {
95
+ foundCommand = currentCommands.find((cmd) => cmd.name === part || cmd.aliases?.includes(part)) || null;
96
+
97
+ if (!foundCommand) {
98
+ return null;
99
+ }
100
+
101
+ // Move to subcommands for next iteration
102
+ currentCommands = foundCommand.commands || [];
103
+ }
104
+
105
+ return foundCommand;
106
+ }