@rapidoc/cli 0.2.1 → 0.2.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.
package/README.md CHANGED
@@ -31,6 +31,7 @@ Node.js 22.12 or later.
31
31
  | `rapidoc validate [spec\|dir]` | Validates one OpenAPI 2.0 / 3.x spec, or every spec in the portal |
32
32
  | `rapidoc lint [spec\|dir]` | Checks what a spec needs for a good portal: operationIds, summaries, examples |
33
33
  | `rapidoc bundle <spec>` | Joins a spec split over several files into one |
34
+ | `rapidoc pdf <spec>` | Writes the API reference of a spec as a PDF (needs `rapipdf`) |
34
35
  | `rapidoc mcp <export\|serve> <spec>` | Turns a spec into MCP tools: export a server project, or serve over stdio |
35
36
  | `rapidoc migrate` | Converts a Redocly or Zudoku project to `rapidoc.config.yaml` |
36
37
  | `rapidoc doctor [dir]` | Checks Node, package versions, the portal config and the browser bundle |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rapidoc/cli",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "The rapidoc command: developer portal dev/build/serve/init, OpenAPI validation and config migration",
5
5
  "homepage": "https://portal.rapidocui.com",
6
6
  "bugs": {
@@ -29,17 +29,18 @@
29
29
  },
30
30
  "dependencies": {
31
31
  "@clack/prompts": "^1.8.1",
32
- "@rapidoc/mcp": "^0.2.1",
32
+ "@rapidoc/mcp": "^0.2.2",
33
33
  "@scalar/openapi-validator": "^0.1.18",
34
- "create-rapidoc": "^0.2.1",
35
- "rapidoc": "^13.1.0",
34
+ "create-rapidoc": "^0.2.2",
35
+ "rapidoc": "^14.0.0",
36
36
  "yaml": "^2.9.1"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@modelcontextprotocol/sdk": "^1.32.2",
40
- "@rapidoc/mock": "^0.2.1",
41
- "@rapidoc/portal": "^0.2.1",
42
- "@rapidoc/server": "^0.2.1"
40
+ "@rapidoc/mock": "^0.2.2",
41
+ "@rapidoc/portal": "^0.2.2",
42
+ "@rapidoc/server": "^0.2.2",
43
+ "rapipdf": "^3.0.0"
43
44
  },
44
45
  "peerDependenciesMeta": {
45
46
  "@modelcontextprotocol/sdk": {
@@ -53,6 +54,9 @@
53
54
  },
54
55
  "@rapidoc/server": {
55
56
  "optional": true
57
+ },
58
+ "rapipdf": {
59
+ "optional": true
56
60
  }
57
61
  },
58
62
  "engines": {
@@ -0,0 +1,221 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { loadPdf, loadPortal } from "../lib/engines.js";
4
+ import { ProblemError, UsageError } from "../lib/errors.js";
5
+ import { icon, info, success } from "../lib/output.js";
6
+
7
+ /*
8
+ * rapidoc pdf <spec>: the API reference of a spec as a PDF, the document <rapi-pdf> makes in the
9
+ * browser: a cover page, a table of contents, the security schemes and every operation with its
10
+ * parameters, request bodies and responses. rapipdf (an optional peer) does the work.
11
+ */
12
+
13
+ const isUrl = (target) => /^https?:\/\//i.test(target);
14
+ /** A URL as is; a path relative to the current folder, or absolute when it's outside it. */
15
+ function displayPath(location) {
16
+ if (isUrl(location)) return location;
17
+ const relative = path.relative(process.cwd(), location);
18
+ return relative.startsWith("..") ? location : relative || ".";
19
+ }
20
+
21
+ /** The spec of the API `id` in the portal config of the current folder. */
22
+ async function specOfApi(id) {
23
+ const portal = await loadPortal("pdf --api");
24
+ let config;
25
+ try {
26
+ ({ config } = await portal.loadConfig(process.cwd()));
27
+ } catch (err) {
28
+ throw new ProblemError(err.message);
29
+ }
30
+ const api = (config.apis ?? []).find((entry) => entry.id === id);
31
+ if (!api) {
32
+ const ids = (config.apis ?? []).map((entry) => entry.id).join(", ") || "none";
33
+ throw new ProblemError(`No API "${id}" in rapidoc.config.* (APIs: ${ids})`);
34
+ }
35
+ const [version] = api.versions;
36
+ return version.isRemote ? version.spec : version.fullPath;
37
+ }
38
+
39
+ /** `openapi.yaml` → `openapi.pdf` in the current folder; a URL's last path segment likewise. */
40
+ function defaultOutput(entry) {
41
+ const name = isUrl(entry) ? new URL(entry).pathname.split("/").filter(Boolean).pop() : entry;
42
+ const base = path.basename(name ?? "", path.extname(name ?? "")) || "api";
43
+ return `${base}.pdf`;
44
+ }
45
+
46
+ /** The labels file: a JSON object of label name to text. */
47
+ function readLabels(file) {
48
+ const location = path.resolve(file);
49
+ if (!fs.existsSync(location)) throw new ProblemError(`File not found: ${location}`);
50
+ let labels;
51
+ try {
52
+ labels = JSON.parse(fs.readFileSync(location, "utf8"));
53
+ } catch (err) {
54
+ throw new ProblemError(`${displayPath(location)} is not valid JSON: ${err.message}`);
55
+ }
56
+ if (labels === null || typeof labels !== "object" || Array.isArray(labels))
57
+ throw new ProblemError(`${displayPath(location)} must be a JSON object of label to text`);
58
+ return labels;
59
+ }
60
+
61
+ export default {
62
+ name: "pdf",
63
+ usage: "pdf <spec>",
64
+ summary: "Writes the API reference of a spec as a PDF",
65
+ description:
66
+ "Loads the spec (OpenAPI 3.x or Swagger 2.0, a file or a URL, with the files its $refs reach) and\nwrites a PDF: a cover page, a table of contents, the security schemes and every operation with its\nparameters, request bodies and responses. The same document <rapi-pdf> makes in the browser.",
67
+ positionals: { name: "spec", max: 1 },
68
+ options: {
69
+ output: {
70
+ type: "string",
71
+ short: "o",
72
+ value: "file",
73
+ description: "Write here (default: the spec's name with .pdf, in the current folder)",
74
+ },
75
+ api: {
76
+ type: "string",
77
+ value: "id",
78
+ description: "Use the spec of this API from rapidoc.config.* instead of a file",
79
+ },
80
+ title: {
81
+ type: "string",
82
+ value: "text",
83
+ description: 'Title on the cover page (default: "API Reference")',
84
+ },
85
+ footer: {
86
+ type: "string",
87
+ value: "text",
88
+ description: "Text at the bottom left of every page",
89
+ },
90
+ "schema-style": {
91
+ type: "string",
92
+ value: "style",
93
+ choices: ["object", "table"],
94
+ description: "Schemas as an indented object tree or as a table (default: object)",
95
+ },
96
+ examples: {
97
+ type: "boolean",
98
+ description: "Include request and response examples",
99
+ },
100
+ "api-list": {
101
+ type: "boolean",
102
+ description: "Add a closing list of every operation, by tag",
103
+ },
104
+ info: {
105
+ type: "boolean",
106
+ negatable: true,
107
+ default: true,
108
+ description: "Leave out the cover page",
109
+ },
110
+ toc: {
111
+ type: "boolean",
112
+ negatable: true,
113
+ default: true,
114
+ description: "Leave out the table of contents",
115
+ },
116
+ security: {
117
+ type: "boolean",
118
+ negatable: true,
119
+ default: true,
120
+ description: "Leave out the security schemes",
121
+ },
122
+ "api-details": {
123
+ type: "boolean",
124
+ negatable: true,
125
+ default: true,
126
+ description: "Leave out the operations",
127
+ },
128
+ "sort-tags": {
129
+ type: "boolean",
130
+ negatable: true,
131
+ default: true,
132
+ description: "Keep the tags in the spec's order instead of sorting them by name",
133
+ },
134
+ "primary-color": {
135
+ type: "string",
136
+ value: "color",
137
+ description: "Color of headings and operation titles (default: #b44646)",
138
+ },
139
+ "alternate-color": {
140
+ type: "string",
141
+ value: "color",
142
+ description: "Color of section labels and table headers (default: #005b96)",
143
+ },
144
+ labels: {
145
+ type: "string",
146
+ value: "file",
147
+ description: "A JSON file of labels to replace, for a PDF in another language",
148
+ },
149
+ font: {
150
+ type: "string",
151
+ value: "file",
152
+ description: "A .ttf or .otf font in place of Roboto (for Chinese, Japanese, Korean, ...)",
153
+ },
154
+ "mono-font": {
155
+ type: "string",
156
+ value: "file",
157
+ description: "A .ttf or .otf font in place of Roboto Mono",
158
+ },
159
+ },
160
+ examples: [
161
+ "rapidoc pdf openapi.yaml",
162
+ "rapidoc pdf openapi.yaml -o dist/reference.pdf --title 'Orders API' --examples",
163
+ "rapidoc pdf https://example.com/openapi.json --schema-style table",
164
+ "rapidoc pdf --api orders -o orders.pdf",
165
+ ],
166
+
167
+ async run({ values, positionals }) {
168
+ const [target] = positionals;
169
+ if (target && values.api)
170
+ throw new UsageError("Give a spec or --api <id>, not both", { command: "pdf" });
171
+ if (!target && !values.api)
172
+ throw new UsageError("rapidoc pdf needs a spec: rapidoc pdf <spec>", { command: "pdf" });
173
+
174
+ let entry = values.api ? await specOfApi(values.api) : target;
175
+ if (!isUrl(entry)) {
176
+ entry = path.resolve(entry);
177
+ if (!fs.existsSync(entry) || !fs.statSync(entry).isFile())
178
+ throw new ProblemError(`File not found: ${entry}`);
179
+ }
180
+ for (const font of [values.font, values["mono-font"]]) {
181
+ if (font && !fs.existsSync(path.resolve(font)))
182
+ throw new ProblemError(`Font file not found: ${path.resolve(font)}`);
183
+ }
184
+ const localize = values.labels ? readLabels(values.labels) : undefined;
185
+
186
+ const { generatePdf } = await loadPdf();
187
+ const options = {
188
+ includeInfo: values.info,
189
+ includeToc: values.toc,
190
+ includeSecurity: values.security,
191
+ includeApiDetails: values["api-details"],
192
+ includeApiList: Boolean(values["api-list"]),
193
+ includeExample: Boolean(values.examples),
194
+ pdfSortTags: values["sort-tags"],
195
+ ...(values.title !== undefined ? { pdfTitle: values.title } : {}),
196
+ ...(values.footer !== undefined ? { pdfFooterText: values.footer } : {}),
197
+ ...(values["schema-style"] ? { pdfSchemaStyle: values["schema-style"] } : {}),
198
+ ...(values["primary-color"] ? { pdfPrimaryColor: values["primary-color"] } : {}),
199
+ ...(values["alternate-color"] ? { pdfAlternateColor: values["alternate-color"] } : {}),
200
+ ...(localize ? { localize } : {}),
201
+ ...(values.font ? { font: values.font } : {}),
202
+ ...(values["mono-font"] ? { monoFont: values["mono-font"] } : {}),
203
+ };
204
+
205
+ let pdf;
206
+ try {
207
+ pdf = await generatePdf(entry, options);
208
+ } catch (err) {
209
+ throw new ProblemError(`${displayPath(entry)}: ${err.message}`);
210
+ }
211
+
212
+ const output = path.resolve(values.output ?? defaultOutput(entry));
213
+ fs.mkdirSync(path.dirname(output), { recursive: true });
214
+ fs.writeFileSync(output, pdf);
215
+
216
+ const pages = (pdf.toString("latin1").match(/\/Type \/Page\b/g) ?? []).length;
217
+ const size = (pdf.length / 1024).toFixed(1);
218
+ info(`\n${icon("📄")}${displayPath(entry)} → ${displayPath(output)}`);
219
+ success(`${pages} page(s), ${size} KB.\n`, " ");
220
+ },
221
+ };
package/src/index.js CHANGED
@@ -20,6 +20,7 @@ import serve from "./commands/serve.js";
20
20
  import mock from "./commands/mock.js";
21
21
  import validate from "./commands/validate.js";
22
22
  import bundle from "./commands/bundle.js";
23
+ import pdf from "./commands/pdf.js";
23
24
  import lint from "./commands/lint.js";
24
25
  import migrate from "./commands/migrate.js";
25
26
  import preview from "./commands/preview.js";
@@ -37,6 +38,7 @@ const COMMANDS = [
37
38
  validate,
38
39
  lint,
39
40
  bundle,
41
+ pdf,
40
42
  mcp,
41
43
  migrate,
42
44
  doctor,
@@ -3,7 +3,7 @@ import { ProblemError } from "./errors.js";
3
3
  /*
4
4
  * The engines behind the commands are optional peers, imported only by the commands that need them:
5
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.
6
+ * (serve), @rapidoc/mock (mock) and rapipdf (pdf). Never import them at the top of a module.
7
7
  * RAPIDOC_PORTAL_MODULE, RAPIDOC_SERVER_MODULE and RAPIDOC_MOCK_MODULE swap the module names (tests use
8
8
  * them to simulate a missing engine).
9
9
  */
@@ -55,6 +55,29 @@ export async function loadMock() {
55
55
  return mock;
56
56
  }
57
57
 
58
+ // RapiPdf's Node entry, for `rapidoc pdf` only. RAPIDOC_PDF_MODULE swaps the module name (tests use
59
+ // it to simulate a missing package).
60
+ const PDF_MODULE = process.env.RAPIDOC_PDF_MODULE || "rapipdf";
61
+
62
+ export async function loadPdf() {
63
+ let pdf;
64
+ try {
65
+ pdf = await tryImport(`${PDF_MODULE}/node`, PDF_MODULE);
66
+ } catch (err) {
67
+ // rapipdf 2.x is the browser element only: it has no ./node entry
68
+ if (err.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw err;
69
+ throw new ProblemError(
70
+ "`rapidoc pdf` needs rapipdf 3 or later. Update it next to the CLI:\n npm install -D rapipdf@latest",
71
+ );
72
+ }
73
+ if (!pdf) {
74
+ throw new ProblemError(
75
+ "`rapidoc pdf` needs rapipdf. Install it next to the CLI:\n npm install -D rapipdf",
76
+ );
77
+ }
78
+ return pdf;
79
+ }
80
+
58
81
  // The MCP SDK, for `rapidoc mcp serve` only (export writes a project that installs it itself).
59
82
  // RAPIDOC_MCP_SDK_MODULE swaps the module name (tests use it to simulate a missing SDK).
60
83
  const MCP_SDK_MODULE = process.env.RAPIDOC_MCP_SDK_MODULE || "@modelcontextprotocol/sdk";