@rapidoc/cli 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE.txt +22 -0
  2. package/README.md +57 -2
  3. package/package.json +59 -4
  4. package/src/bundle/components.js +187 -0
  5. package/src/bundle/dereference.js +67 -0
  6. package/src/bundle/write.js +20 -0
  7. package/src/commands/build.js +59 -0
  8. package/src/commands/bundle.js +187 -0
  9. package/src/commands/completion.js +37 -0
  10. package/src/commands/dev.js +51 -0
  11. package/src/commands/doctor.js +214 -0
  12. package/src/commands/init.js +163 -0
  13. package/src/commands/lint.js +160 -0
  14. package/src/commands/mcp.js +190 -0
  15. package/src/commands/migrate.js +112 -0
  16. package/src/commands/mock.js +200 -0
  17. package/src/commands/preview.js +218 -0
  18. package/src/commands/serve.js +95 -0
  19. package/src/commands/validate.js +139 -0
  20. package/src/index.js +126 -0
  21. package/src/lib/args.js +156 -0
  22. package/src/lib/completion.js +222 -0
  23. package/src/lib/engines.js +74 -0
  24. package/src/lib/errors.js +32 -0
  25. package/src/lib/help.js +75 -0
  26. package/src/lib/open.js +23 -0
  27. package/src/lib/openapi-shape.js +110 -0
  28. package/src/lib/output.js +38 -0
  29. package/src/lib/ports.js +65 -0
  30. package/src/lib/prompt.js +73 -0
  31. package/src/lib/suggest.js +36 -0
  32. package/src/lint/config.js +112 -0
  33. package/src/lint/rules/index.js +40 -0
  34. package/src/lint/rules/info-contact.js +12 -0
  35. package/src/lint/rules/info-license.js +11 -0
  36. package/src/lint/rules/media-example.js +35 -0
  37. package/src/lint/rules/no-server-example-com.js +30 -0
  38. package/src/lint/rules/no-unused-components.js +41 -0
  39. package/src/lint/rules/operation-2xx-response.js +17 -0
  40. package/src/lint/rules/operation-4xx-response.js +17 -0
  41. package/src/lint/rules/operation-description.js +12 -0
  42. package/src/lint/rules/operation-operationId-unique.js +24 -0
  43. package/src/lint/rules/operation-operationId-url-safe.js +18 -0
  44. package/src/lint/rules/operation-operationId.js +12 -0
  45. package/src/lint/rules/operation-summary.js +12 -0
  46. package/src/lint/rules/operation-tag-defined.js +22 -0
  47. package/src/lint/rules/path-kebab-case.js +16 -0
  48. package/src/lint/rules/security-defined.js +23 -0
  49. package/src/lint/rules/security-scheme-defined.js +28 -0
  50. package/src/lint/rules/tag-description.js +11 -0
  51. package/src/lint/run.js +50 -0
  52. package/src/lint/traverse.js +114 -0
  53. package/src/lint/types.js +46 -0
  54. package/src/validate/bundle.js +238 -0
  55. package/src/validate/check.js +122 -0
  56. package/src/validate/report.js +140 -0
@@ -0,0 +1,156 @@
1
+ import { parseArgs } from "node:util";
2
+ import { UsageError } from "./errors.js";
3
+ import { closest } from "./suggest.js";
4
+
5
+ /**
6
+ * Options every command accepts. `--version` is only a top-level flag (`rapidoc --version`).
7
+ */
8
+ export const GLOBAL_OPTIONS = {
9
+ help: { type: "boolean", short: "h", description: "Show this command's help" },
10
+ quiet: { type: "boolean", short: "q", description: "Print errors and warnings only" },
11
+ yes: {
12
+ type: "boolean",
13
+ short: "y",
14
+ description: "Don't ask: take the default answer to every question",
15
+ },
16
+ };
17
+
18
+ /** How an option is written: `--out-dir <path>`, `-f, --force`, `--no-install`. */
19
+ export function optionLabel(name, def) {
20
+ if (def.type === "boolean" && def.negatable) return `--no-${name}`;
21
+ const long = `--${name}${def.type === "string" ? ` <${def.value || "value"}>` : ""}`;
22
+ return def.short ? `-${def.short}, ${long}` : long;
23
+ }
24
+
25
+ const spellings = (defs) =>
26
+ Object.entries(defs).flatMap(([name, def]) =>
27
+ def.type === "boolean" && def.negatable ? [`--${name}`, `--no-${name}`] : [`--${name}`],
28
+ );
29
+
30
+ function unknownOption(raw, defs, command) {
31
+ const suggestion = raw.startsWith("--") ? closest(raw, spellings(defs)) : undefined;
32
+ return new UsageError(
33
+ `Unknown option ${raw}.${suggestion ? ` Did you mean ${suggestion}?` : ""}`,
34
+ { command },
35
+ );
36
+ }
37
+
38
+ /** Checks a string value against the option's `kind` and `choices`; returns the value to use. */
39
+ function checkValue(name, def, value, command) {
40
+ if (def.kind === "int" || def.kind === "port") {
41
+ const number = Number(value);
42
+ const max = def.kind === "port" ? 65535 : Number.MAX_SAFE_INTEGER;
43
+ if (value.trim() === "" || !Number.isInteger(number) || number < 0 || number > max) {
44
+ const range = def.kind === "port" ? " from 0 to 65535" : "";
45
+ throw new UsageError(`--${name} needs a whole number${range}, got "${value}"`, { command });
46
+ }
47
+ return number;
48
+ }
49
+ if (def.choices) {
50
+ const match = def.choices.find((choice) => choice === value.toLowerCase());
51
+ if (!match) {
52
+ const suggestion = closest(value, def.choices);
53
+ throw new UsageError(
54
+ `--${name} must be one of ${def.choices.join(", ")}, got "${value}".${suggestion ? ` Did you mean ${suggestion}?` : ""}`,
55
+ { command },
56
+ );
57
+ }
58
+ return match;
59
+ }
60
+ return value;
61
+ }
62
+
63
+ /**
64
+ * Parses a command's arguments (everything after the command name) against its declared options:
65
+ *
66
+ * options: { "out-dir": { type: "string", value: "path", default: "dist", description },
67
+ * port: { type: "string", kind: "port" }, force: { type: "boolean", short: "f" },
68
+ * install: { type: "boolean", negatable: true, default: true }, from: { type: "string",
69
+ * choices: ["redocly", "zudoku"], required: true } }
70
+ * positionals: { name: "dir", max: 1 }
71
+ *
72
+ * Positionals may come anywhere. Unknown options, missing or malformed values, bad choices and extra
73
+ * positionals throw a UsageError (exit 2). Returns { values, positionals }; values are keyed by option
74
+ * name (`values["out-dir"]`), with defaults filled in and numbers converted.
75
+ */
76
+ export function parseCommandArgs(command, argv) {
77
+ const defs = { ...command.options, ...GLOBAL_OPTIONS };
78
+ const parseOptions = Object.fromEntries(
79
+ Object.entries(defs).map(([name, def]) => [
80
+ name,
81
+ { type: def.type, ...(def.short && { short: def.short }) },
82
+ ]),
83
+ );
84
+
85
+ let parsed;
86
+ try {
87
+ parsed = parseArgs({
88
+ args: argv,
89
+ options: parseOptions,
90
+ allowPositionals: true,
91
+ allowNegative: true,
92
+ strict: false,
93
+ tokens: true,
94
+ });
95
+ } catch (err) {
96
+ throw new UsageError(err.message, { command: command.name });
97
+ }
98
+
99
+ const values = {};
100
+ for (const token of parsed.tokens) {
101
+ if (token.kind !== "option") continue;
102
+ const def = defs[token.name];
103
+ if (!def) throw unknownOption(token.rawName, defs, command.name);
104
+ const negated = token.rawName !== `--${token.name}` && token.rawName.startsWith("--no-");
105
+
106
+ if (def.type === "boolean") {
107
+ if (negated && !def.negatable) throw unknownOption(token.rawName, defs, command.name);
108
+ if (token.value !== undefined && token.value !== null)
109
+ throw new UsageError(`${token.rawName} takes no value`, { command: command.name });
110
+ values[token.name] = !negated;
111
+ continue;
112
+ }
113
+
114
+ if (negated) throw unknownOption(token.rawName, defs, command.name);
115
+ const missing =
116
+ token.value === undefined ||
117
+ token.value === null ||
118
+ (!token.inlineValue && token.value.startsWith("-") && token.value !== "-");
119
+ if (missing) {
120
+ throw new UsageError(
121
+ `--${token.name} needs a value (--${token.name} <${def.value || "value"}>)`,
122
+ {
123
+ command: command.name,
124
+ },
125
+ );
126
+ }
127
+ const value = checkValue(token.name, def, token.value, command.name);
128
+ if (def.multiple) (values[token.name] ??= []).push(value);
129
+ else values[token.name] = value;
130
+ }
131
+
132
+ for (const [name, def] of Object.entries(defs)) {
133
+ if (values[name] !== undefined) continue;
134
+ if (def.required && !values.help)
135
+ throw new UsageError(`rapidoc ${command.name} needs ${optionLabel(name, def)}`, {
136
+ command: command.name,
137
+ });
138
+ if (def.default !== undefined) values[name] = def.default;
139
+ }
140
+
141
+ const positionals = parsed.positionals;
142
+ const max = command.positionals?.max ?? 0;
143
+ if (positionals.length > max && !values.help) {
144
+ const extra = positionals
145
+ .slice(max)
146
+ .map((arg) => `"${arg}"`)
147
+ .join(", ");
148
+ const takes =
149
+ max === 0 ? "takes no arguments" : `takes ${command.usage.split(" ").slice(1).join(" ")}`;
150
+ throw new UsageError(`Unexpected argument ${extra}: rapidoc ${command.name} ${takes}`, {
151
+ command: command.name,
152
+ });
153
+ }
154
+
155
+ return { values, positionals };
156
+ }
@@ -0,0 +1,222 @@
1
+ import { GLOBAL_OPTIONS } from "./args.js";
2
+
3
+ /*
4
+ * Shell completion scripts for zsh, bash and fish, generated from the command declarations (the same
5
+ * `options` and `positionals` that make the help), so they can't drift from the commands. Each script
6
+ * is self-contained: completing never runs the CLI.
7
+ *
8
+ * What is completed: command names (with their summaries where the shell shows them), each command's
9
+ * options (long and short, `--no-` forms of negatable ones), the values of options with `choices`,
10
+ * files for options whose value is a file or path, and positionals: `positionals.choices` for the first
11
+ * one (mcp's export|serve), files otherwise.
12
+ */
13
+
14
+ const FILE_VALUES = new Set(["file", "path", "dir", "spec", "dist", "spec|dir"]);
15
+
16
+ /** The options of a command, global ones included, as flat records. */
17
+ function optionsOf(command) {
18
+ return Object.entries({ ...command.options, ...GLOBAL_OPTIONS }).map(([name, def]) => ({
19
+ name,
20
+ short: def.short,
21
+ takesValue: def.type === "string",
22
+ choices: def.choices,
23
+ files: def.type === "string" && FILE_VALUES.has(def.value),
24
+ negatable: Boolean(def.negatable),
25
+ multiple: Boolean(def.multiple),
26
+ description: (def.description ?? "").replace(/\s*\n\s*/g, " "),
27
+ }));
28
+ }
29
+
30
+ const flagsOf = (option) => [
31
+ `--${option.name}`,
32
+ ...(option.negatable ? [`--no-${option.name}`] : []),
33
+ ...(option.short ? [`-${option.short}`] : []),
34
+ ];
35
+
36
+ const sq = (text) => `'${String(text).replace(/'/g, "'\\''")}'`;
37
+
38
+ // ---------------------------------------------------------------------------------------------- zsh
39
+
40
+ const zshDescription = (text) => String(text).replace(/[[\]:]/g, "\\$&");
41
+
42
+ function zshOption(option) {
43
+ const desc = `[${zshDescription(option.description)}]`;
44
+ const star = option.multiple ? "*" : "";
45
+ let value = "";
46
+ if (option.takesValue) {
47
+ const action = option.choices ? `(${option.choices.join(" ")})` : option.files ? "_files" : "";
48
+ value = `:${option.name}:${action}`;
49
+ }
50
+ if (option.short && !option.negatable)
51
+ return `${sq(`(-${option.short} --${option.name})`)}{-${option.short},--${option.name}}${sq(`${desc}${value}`)}`;
52
+ const forms = option.negatable
53
+ ? [`--${option.name}`, `--no-${option.name}`]
54
+ : [`--${option.name}`];
55
+ return forms.map((form) => sq(`${star}${form}${desc}${value}`)).join(" ");
56
+ }
57
+
58
+ function zshPositionals(command) {
59
+ const spec = command.positionals;
60
+ if (!spec) return [];
61
+ const out = [];
62
+ if (spec.choices) out.push(sq(`1:${spec.name}:(${spec.choices.join(" ")})`));
63
+ out.push(sq(`*:${spec.choices ? "file" : spec.name}:_files`));
64
+ return out;
65
+ }
66
+
67
+ export function zsh(commands) {
68
+ const names = commands
69
+ .map((command) => sq(`${command.name}:${zshDescription(command.summary)}`))
70
+ .join("\n ");
71
+ const cases = commands
72
+ .map(
73
+ (command) =>
74
+ ` ${command.name})\n _arguments -s ${[...optionsOf(command).map(zshOption), ...zshPositionals(command)].join(" \\\n ")}\n ;;`,
75
+ )
76
+ .join("\n");
77
+ return `#compdef rapidoc
78
+ # zsh completion for rapidoc, generated by \`rapidoc completion zsh\`.
79
+
80
+ _rapidoc() {
81
+ local -a commands
82
+ commands=(
83
+ ${names}
84
+ 'help:Show help for a command'
85
+ )
86
+ local context state state_descr line
87
+ typeset -A opt_args
88
+ _arguments -C \\
89
+ '(- *)'{-h,--help}'[Show help]' \\
90
+ '(- *)'{-v,--version}'[Show the version]' \\
91
+ '1: :->command' \\
92
+ '*:: :->args' && return
93
+ case $state in
94
+ command) _describe -t commands 'rapidoc command' commands ;;
95
+ args)
96
+ case $words[1] in
97
+ ${cases}
98
+ help) _describe -t commands 'rapidoc command' commands ;;
99
+ esac
100
+ ;;
101
+ esac
102
+ }
103
+
104
+ if [ "$funcstack[1]" = "_rapidoc" ]; then
105
+ _rapidoc "$@"
106
+ else
107
+ compdef _rapidoc rapidoc
108
+ fi
109
+ `;
110
+ }
111
+
112
+ // --------------------------------------------------------------------------------------------- bash
113
+
114
+ export function bash(commands) {
115
+ const names = [...commands.map((command) => command.name), "help"].join(" ");
116
+ const cases = commands
117
+ .map((command) => {
118
+ const options = optionsOf(command);
119
+ const flags = options.flatMap(flagsOf).join(" ");
120
+ const valued = options
121
+ .filter((option) => option.takesValue)
122
+ .map((option) => {
123
+ const forms = flagsOf(option).join("|");
124
+ const action = option.choices
125
+ ? `COMPREPLY=($(compgen -W "${option.choices.join(" ")}" -- "$cur"))`
126
+ : option.files
127
+ ? 'COMPREPLY=($(compgen -f -- "$cur"))'
128
+ : "COMPREPLY=()";
129
+ return ` ${forms}) ${action}; return ;;`;
130
+ })
131
+ .join("\n");
132
+ const first = command.positionals?.choices
133
+ ? ` if [[ $npos -eq 0 && "$cur" != -* ]]; then COMPREPLY=($(compgen -W "${command.positionals.choices.join(" ")}" -- "$cur")); return; fi\n`
134
+ : "";
135
+ const positional = command.positionals
136
+ ? 'COMPREPLY=($(compgen -f -- "$cur"))'
137
+ : "COMPREPLY=()";
138
+ return ` ${command.name})
139
+ case "$prev" in
140
+ ${valued}
141
+ esac
142
+ ${first} if [[ "$cur" == -* ]]; then COMPREPLY=($(compgen -W "${flags}" -- "$cur")); return; fi
143
+ ${positional} ;;`;
144
+ })
145
+ .join("\n");
146
+ return `# bash completion for rapidoc, generated by \`rapidoc completion bash\`.
147
+
148
+ _rapidoc() {
149
+ local cur prev cmd i npos
150
+ COMPREPLY=()
151
+ cur="\${COMP_WORDS[COMP_CWORD]}"
152
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
153
+ cmd=""
154
+ npos=0
155
+ for ((i = 1; i < COMP_CWORD; i++)); do
156
+ case "\${COMP_WORDS[i]}" in
157
+ -*) ;;
158
+ *) if [[ -z "$cmd" ]]; then cmd="\${COMP_WORDS[i]}"; else npos=$((npos + 1)); fi ;;
159
+ esac
160
+ done
161
+ if [[ -z "$cmd" ]]; then
162
+ COMPREPLY=($(compgen -W "${names} --help --version" -- "$cur"))
163
+ return
164
+ fi
165
+ case "$cmd" in
166
+ ${cases}
167
+ help) COMPREPLY=($(compgen -W "${names}" -- "$cur")) ;;
168
+ esac
169
+ }
170
+
171
+ complete -F _rapidoc rapidoc
172
+ `;
173
+ }
174
+
175
+ // --------------------------------------------------------------------------------------------- fish
176
+
177
+ export function fish(commands) {
178
+ const lines = [
179
+ "# fish completion for rapidoc, generated by `rapidoc completion fish`.",
180
+ "",
181
+ "complete -c rapidoc -f",
182
+ ];
183
+ lines.push(
184
+ "complete -c rapidoc -n __fish_use_subcommand -s h -l help -d 'Show help'",
185
+ "complete -c rapidoc -n __fish_use_subcommand -s v -l version -d 'Show the version'",
186
+ );
187
+ for (const command of commands)
188
+ lines.push(
189
+ `complete -c rapidoc -n __fish_use_subcommand -a ${command.name} -d ${sq(command.summary)}`,
190
+ );
191
+ lines.push("complete -c rapidoc -n __fish_use_subcommand -a help -d 'Show help for a command'");
192
+ for (const command of commands) {
193
+ const when = `-n '__fish_seen_subcommand_from ${command.name}'`;
194
+ lines.push("", `# rapidoc ${command.name}`);
195
+ for (const option of optionsOf(command)) {
196
+ const short = option.short && !option.negatable ? ` -s ${option.short}` : "";
197
+ const value = option.takesValue
198
+ ? option.choices
199
+ ? ` -r -a '${option.choices.join(" ")}'`
200
+ : option.files
201
+ ? " -r -F"
202
+ : " -r"
203
+ : "";
204
+ lines.push(
205
+ `complete -c rapidoc ${when}${short} -l ${option.name}${value} -d ${sq(option.description)}`,
206
+ );
207
+ if (option.negatable)
208
+ lines.push(`complete -c rapidoc ${when} -l no-${option.name} -d ${sq(option.description)}`);
209
+ }
210
+ if (command.positionals?.choices)
211
+ lines.push(
212
+ `complete -c rapidoc ${when} -n 'not __fish_seen_subcommand_from ${command.positionals.choices.join(" ")}' -a '${command.positionals.choices.join(" ")}'`,
213
+ );
214
+ if (command.positionals) lines.push(`complete -c rapidoc ${when} -F`);
215
+ }
216
+ lines.push(
217
+ "",
218
+ `complete -c rapidoc -n '__fish_seen_subcommand_from help' -a '${commands.map((c) => c.name).join(" ")}'`,
219
+ "",
220
+ );
221
+ return lines.join("\n");
222
+ }
@@ -0,0 +1,74 @@
1
+ import { ProblemError } from "./errors.js";
2
+
3
+ /*
4
+ * The engines behind the commands are optional peers, imported only by the commands that need them:
5
+ * @rapidoc/portal (dev, build, migrate, folder-wide validate, mock of a portal folder), @rapidoc/server
6
+ * (serve) and @rapidoc/mock (mock). Never import them at the top of a module.
7
+ * RAPIDOC_PORTAL_MODULE, RAPIDOC_SERVER_MODULE and RAPIDOC_MOCK_MODULE swap the module names (tests use
8
+ * them to simulate a missing engine).
9
+ */
10
+
11
+ const PORTAL_MODULE = process.env.RAPIDOC_PORTAL_MODULE || "@rapidoc/portal";
12
+ const SERVER_MODULE = process.env.RAPIDOC_SERVER_MODULE || "@rapidoc/server";
13
+ const MOCK_MODULE = process.env.RAPIDOC_MOCK_MODULE || "@rapidoc/mock";
14
+
15
+ /** The module, or null when its package isn't installed (other import errors are thrown). */
16
+ async function tryImport(specifier, packageName = specifier) {
17
+ try {
18
+ return await import(specifier);
19
+ } catch (err) {
20
+ if (err.code === "ERR_MODULE_NOT_FOUND" && err.message.includes(packageName)) return null;
21
+ throw err;
22
+ }
23
+ }
24
+
25
+ /** The portal engine, or null when it isn't installed (single-spec validate works without it). */
26
+ export const tryLoadPortal = () => tryImport(PORTAL_MODULE);
27
+
28
+ export async function loadPortal(commandName) {
29
+ const portal = await tryLoadPortal();
30
+ if (!portal) {
31
+ throw new ProblemError(
32
+ `\`rapidoc ${commandName}\` needs the portal engine. Install it next to the CLI:\n npm install -D @rapidoc/portal`,
33
+ );
34
+ }
35
+ return portal;
36
+ }
37
+
38
+ export async function loadServer() {
39
+ const server = await tryImport(SERVER_MODULE);
40
+ if (!server) {
41
+ throw new ProblemError(
42
+ "`rapidoc serve` needs @rapidoc/server. Install it next to the CLI:\n npm install @rapidoc/server",
43
+ );
44
+ }
45
+ return server;
46
+ }
47
+
48
+ export async function loadMock() {
49
+ const mock = await tryImport(MOCK_MODULE);
50
+ if (!mock) {
51
+ throw new ProblemError(
52
+ "`rapidoc mock` needs @rapidoc/mock. Install it next to the CLI:\n npm install -D @rapidoc/mock",
53
+ );
54
+ }
55
+ return mock;
56
+ }
57
+
58
+ // The MCP SDK, for `rapidoc mcp serve` only (export writes a project that installs it itself).
59
+ // RAPIDOC_MCP_SDK_MODULE swaps the module name (tests use it to simulate a missing SDK).
60
+ const MCP_SDK_MODULE = process.env.RAPIDOC_MCP_SDK_MODULE || "@modelcontextprotocol/sdk";
61
+
62
+ export async function loadMcpSdk() {
63
+ const [server, stdio, types] = await Promise.all([
64
+ tryImport(`${MCP_SDK_MODULE}/server/index.js`, MCP_SDK_MODULE),
65
+ tryImport(`${MCP_SDK_MODULE}/server/stdio.js`, MCP_SDK_MODULE),
66
+ tryImport(`${MCP_SDK_MODULE}/types.js`, MCP_SDK_MODULE),
67
+ ]);
68
+ if (!server || !stdio || !types) {
69
+ throw new ProblemError(
70
+ "`rapidoc mcp serve` needs the MCP SDK. Install it next to the CLI:\n npm install -D @modelcontextprotocol/sdk",
71
+ );
72
+ }
73
+ return { Server: server.Server, StdioServerTransport: stdio.StdioServerTransport, ...types };
74
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The ways a command stops early, and the exit code each one means:
3
+ * - UsageError (2): the command line is wrong (unknown command or option, bad or missing value).
4
+ * - ProblemError (1): the input has problems (invalid spec or config, failed build, missing engine).
5
+ * - CancelledError (130): the user cancelled a question.
6
+ * The dispatcher (src/index.js) prints the message and sets the exit code; commands only throw.
7
+ */
8
+ export class UsageError extends Error {
9
+ constructor(message, { command } = {}) {
10
+ super(message);
11
+ this.name = "UsageError";
12
+ this.exitCode = 2;
13
+ this.command = command;
14
+ }
15
+ }
16
+
17
+ /** The user cancelled a question (Ctrl+C): "Cancelled.", exit 130 as for an interrupted command. */
18
+ export class CancelledError extends Error {
19
+ constructor(message = "Cancelled.") {
20
+ super(message);
21
+ this.name = "CancelledError";
22
+ this.exitCode = 130;
23
+ }
24
+ }
25
+
26
+ export class ProblemError extends Error {
27
+ constructor(message) {
28
+ super(message);
29
+ this.name = "ProblemError";
30
+ this.exitCode = 1;
31
+ }
32
+ }
@@ -0,0 +1,75 @@
1
+ import { GLOBAL_OPTIONS, optionLabel } from "./args.js";
2
+
3
+ const NAME = "RapiDoc CLI (@rapidoc/cli) - OpenAPI & Developer Portal Toolkit";
4
+
5
+ function table(rows, indent = " ") {
6
+ const width = Math.max(...rows.map(([left]) => left.length)) + 2;
7
+ return rows
8
+ .map(([left, right]) => {
9
+ const lines = right.split("\n");
10
+ return [
11
+ `${indent}${left.padEnd(width)}${lines[0]}`,
12
+ ...lines.slice(1).map((line) => `${indent}${" ".repeat(width)}${line}`),
13
+ ].join("\n");
14
+ })
15
+ .join("\n");
16
+ }
17
+
18
+ function optionRows(defs) {
19
+ return Object.entries(defs).map(([name, def]) => {
20
+ const extras = [];
21
+ if (def.choices) extras.push(def.choices.join(" | "));
22
+ if (def.default !== undefined && def.type === "string") extras.push(`default ${def.default}`);
23
+ const text = def.description + (extras.length ? ` (${extras.join("; ")})` : "");
24
+ return [optionLabel(name, def), text];
25
+ });
26
+ }
27
+
28
+ /** `rapidoc --help`: every command, the top-level flags, where to read more. */
29
+ export function overviewHelp(commands) {
30
+ return `
31
+ ${NAME}
32
+
33
+ Usage:
34
+ rapidoc <command> [options]
35
+ rapidoc <command> --help Show a command's options and examples
36
+
37
+ Commands:
38
+ ${table(commands.map((command) => [command.usage, command.summary]))}
39
+
40
+ Options:
41
+ ${table([
42
+ ["-h, --help", "Show this help (or a command's, after the command)"],
43
+ ["-v, --version", "Show the version"],
44
+ ["-q, --quiet", "Print errors and warnings only"],
45
+ ["-y, --yes", "Don't ask: take the default answer to every question"],
46
+ ])}
47
+
48
+ In a terminal, commands ask for what their options don't say (\`rapidoc\` alone shows a menu);
49
+ piped, in CI or with --yes they never ask.
50
+
51
+ dev, build, migrate, folder-wide validate and mock of a portal folder need @rapidoc/portal installed next to
52
+ the CLI; serve needs @rapidoc/server; mock needs @rapidoc/mock.
53
+
54
+ Exit codes: 0 success, 1 problems in the input (specs, config, build), 2 a wrong command line.
55
+
56
+ Examples:
57
+ rapidoc init my-portal --title "Acme Developer Portal"
58
+ rapidoc dev
59
+ rapidoc build --out-dir public
60
+ rapidoc validate ./specs/orders-api.yaml
61
+ rapidoc build --help
62
+ `;
63
+ }
64
+
65
+ /** `rapidoc <command> --help`. */
66
+ export function commandHelp(command) {
67
+ const sections = [`\nrapidoc ${command.usage}\n\n ${command.summary}`];
68
+ if (command.description) sections.push(command.description.replace(/^/gm, " "));
69
+ const own = optionRows(command.options || {});
70
+ if (own.length) sections.push(`Options:\n${table(own)}`);
71
+ sections.push(`Global options:\n${table(optionRows(GLOBAL_OPTIONS))}`);
72
+ if (command.examples?.length)
73
+ sections.push(`Examples:\n${command.examples.map((example) => ` ${example}`).join("\n")}`);
74
+ return `${sections.join("\n\n")}\n`;
75
+ }
@@ -0,0 +1,23 @@
1
+ import { spawn } from "node:child_process";
2
+ import { warn } from "./output.js";
3
+
4
+ /**
5
+ * Opens `url` in the default browser (`--open` on dev and preview). Best effort: a failure is a warning,
6
+ * never an error. RAPIDOC_OPEN_COMMAND swaps the command (tests set it to `echo`).
7
+ */
8
+ export function openBrowser(url) {
9
+ const [command, ...args] = process.env.RAPIDOC_OPEN_COMMAND
10
+ ? [process.env.RAPIDOC_OPEN_COMMAND]
11
+ : process.platform === "darwin"
12
+ ? ["open"]
13
+ : process.platform === "win32"
14
+ ? ["cmd", "/c", "start", '""']
15
+ : ["xdg-open"];
16
+ try {
17
+ const child = spawn(command, [...args, url], { stdio: "ignore", detached: true });
18
+ child.on("error", () => warn(`Could not open a browser; open ${url} yourself.`, " "));
19
+ child.unref();
20
+ } catch {
21
+ warn(`Could not open a browser; open ${url} yourself.`, " ");
22
+ }
23
+ }