@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
package/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Mrinmoy Majumdar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @rapidoc/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `rapidoc` command: build a developer portal from OpenAPI specs and Markdown guides, and work with the specs themselves (preview, mock, validate, lint, bundle, MCP).
4
+
5
+ Docs: [portal.rapidocui.com](https://portal.rapidocui.com)
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -D @rapidoc/cli @rapidoc/portal
11
+ ```
12
+
13
+ Or start a new portal, with both packages already listed:
14
+
15
+ ```bash
16
+ npm create rapidoc@latest my-portal
17
+ ```
18
+
19
+ Node.js 22.12 or later.
20
+
21
+ ## Commands
22
+
23
+ | Command | What it does |
24
+ | :----------------------------------- | :---------------------------------------------------------------------------- |
25
+ | `rapidoc init [dir]` | Scaffolds a portal, using the OpenAPI files already in the folder |
26
+ | `rapidoc dev [dir]` | Development server with live reload |
27
+ | `rapidoc build [dir]` | Builds the static portal into `dist/` |
28
+ | `rapidoc serve [dist]` | Serves a built portal and enforces sign-in and access rules |
29
+ | `rapidoc preview <spec>` | Shows one spec in `<rapi-doc>`, reloading on save (no portal needed) |
30
+ | `rapidoc mock [dir\|spec…]` | Mock server for the portal's APIs, each under `/<api id>` |
31
+ | `rapidoc validate [spec\|dir]` | Validates one OpenAPI 2.0 / 3.x spec, or every spec in the portal |
32
+ | `rapidoc lint [spec\|dir]` | Checks what a spec needs for a good portal: operationIds, summaries, examples |
33
+ | `rapidoc bundle <spec>` | Joins a spec split over several files into one |
34
+ | `rapidoc mcp <export\|serve> <spec>` | Turns a spec into MCP tools: export a server project, or serve over stdio |
35
+ | `rapidoc migrate` | Converts a Redocly or Zudoku project to `rapidoc.config.yaml` |
36
+ | `rapidoc doctor [dir]` | Checks Node, package versions, the portal config and the browser bundle |
37
+ | `rapidoc completion <shell>` | Prints a completion script for zsh, bash or fish |
38
+
39
+ `rapidoc <command> --help` lists a command's options and examples. In a terminal, commands ask for what their options don't say; in CI, piped, or with `--yes` they never ask.
40
+
41
+ ## Optional packages
42
+
43
+ The CLI loads these only for the commands that need them:
44
+
45
+ | Package | Needed by |
46
+ | :-------------------------- | :----------------------------------------------------------- |
47
+ | `@rapidoc/portal` | `dev`, `build`, `migrate`, folder-wide `validate` and `mock` |
48
+ | `@rapidoc/server` | `serve` |
49
+ | `@rapidoc/mock` | `mock` |
50
+ | `@modelcontextprotocol/sdk` | `mcp serve` |
51
+
52
+ ## Exit codes
53
+
54
+ `0` success, `1` problems in the input (specs, config, build), `2` a wrong command line.
55
+
56
+ ## License
57
+
58
+ MIT
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@rapidoc/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "The rapidoc command: developer portal dev/build/serve/init, OpenAPI validation and config migration",
5
+ "homepage": "https://portal.rapidocui.com",
6
+ "bugs": {
7
+ "url": "https://github.com/rapi-doc/RapiDoc/issues"
8
+ },
9
+ "license": "MIT",
10
+ "author": "Mrinmoy Majumdar <mrin9@yahoo.com>",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/rapi-doc/RapiDoc.git",
14
+ "directory": "packages/rapidoc-cli"
15
+ },
16
+ "bin": {
17
+ "rapidoc": "src/index.js"
18
+ },
19
+ "files": [
20
+ "src"
21
+ ],
22
+ "type": "module",
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "start": "node src/index.js",
28
+ "test": "node --test tests/**/*.test.js"
29
+ },
30
+ "dependencies": {
31
+ "@clack/prompts": "^1.8.1",
32
+ "@rapidoc/mcp": "^0.1.2",
33
+ "@scalar/openapi-validator": "^0.1.18",
34
+ "create-rapidoc": "^0.1.2",
35
+ "rapidoc": "^12.1.0",
36
+ "yaml": "^2.9.1"
37
+ },
38
+ "peerDependencies": {
39
+ "@modelcontextprotocol/sdk": "^1.32.2",
40
+ "@rapidoc/mock": "^0.1.2",
41
+ "@rapidoc/portal": "^0.1.2",
42
+ "@rapidoc/server": "^0.1.2"
43
+ },
44
+ "peerDependenciesMeta": {
45
+ "@modelcontextprotocol/sdk": {
46
+ "optional": true
47
+ },
48
+ "@rapidoc/mock": {
49
+ "optional": true
50
+ },
51
+ "@rapidoc/portal": {
52
+ "optional": true
53
+ },
54
+ "@rapidoc/server": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "engines": {
59
+ "node": ">=22.12.0"
60
+ }
61
+ }
@@ -0,0 +1,187 @@
1
+ import path from "node:path";
2
+ import { childKind, CONTAINERS } from "../lib/openapi-shape.js";
3
+ import { encodePointer, isUrl, resolveRef, valueAt } from "../validate/bundle.js";
4
+
5
+ /*
6
+ * Turns a spec split over several files into one document: every $ref to another file becomes a
7
+ * component (`#/components/schemas/Order`, or `#/definitions/Order` in Swagger 2.0) holding a copy of
8
+ * what it pointed to, rewritten the same way. In-file $refs stay as written. A $ref whose kind can't be
9
+ * told from where it is (under a vendor extension, say) is inlined instead.
10
+ *
11
+ * The walk knows the OpenAPI structure (which children of a node are schemas, parameters, ...), so the
12
+ * kind of a $ref is the kind of the place it's written in.
13
+ */
14
+
15
+ /** @typedef {import("../validate/bundle.js").SpecFile} SpecFile */
16
+ /** @typedef {{ location: string, pointer: string[], message: string }} RefProblem */
17
+
18
+ /** Where a component of `kind` lives, as pointer segments, or undefined when the version has no place for it. */
19
+ function containerFor(kind, { v2, pathItems }) {
20
+ if (v2)
21
+ return { schema: ["definitions"], parameter: ["parameters"], response: ["responses"] }[kind];
22
+ if (kind === "pathItem" && !pathItems) return undefined;
23
+ const container = Object.keys(CONTAINERS).find((key) => CONTAINERS[key] === kind);
24
+ return container ? ["components", container] : undefined;
25
+ }
26
+
27
+ /** A component name from where a $ref points: the file name, or the last pointer segment. */
28
+ function nameFor(location, pointer) {
29
+ const raw = pointer.length
30
+ ? pointer.at(-1)
31
+ : path
32
+ .basename(isUrl(location) ? new URL(location).pathname : location)
33
+ .replace(/\.[^.]+$/, "");
34
+ return raw.replace(/[^a-zA-Z0-9._-]/g, "_") || "component";
35
+ }
36
+
37
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
38
+
39
+ /**
40
+ * The entry file of `files` as one document, other-file $refs turned into components.
41
+ * @param {{ entry: string, files: Map<string, SpecFile>, skipped: string[] }} loaded
42
+ * @returns {{ value: object, problems: RefProblem[], added: { kind: string, name: string, from: string }[], inlined: number }}
43
+ */
44
+ export function toComponents({ entry, files }) {
45
+ const root = files.get(entry).value;
46
+ const v2 = isObject(root) && typeof root.swagger === "string";
47
+ const pathItems = !v2 && /^3\.[1-9]/.test(String(root?.openapi ?? ""));
48
+ const versions = { v2, pathItems };
49
+
50
+ /** @type {RefProblem[]} */
51
+ const problems = [];
52
+ const added = [];
53
+ let inlined = 0;
54
+ /** target key (location + pointer) → component pointer segments */
55
+ const named = new Map();
56
+ /** container pointer (joined) → names taken there, with the target key each holds */
57
+ const taken = new Map();
58
+ /** container pointer (joined) → { name: value } to merge into the output */
59
+ const components = new Map();
60
+
61
+ const takenIn = (container) => {
62
+ const key = container.join("/");
63
+ if (!taken.has(key)) {
64
+ const existing = valueAt(root, container);
65
+ taken.set(
66
+ key,
67
+ new Map(Object.keys(isObject(existing) ? existing : {}).map((n) => [n, null])),
68
+ );
69
+ components.set(key, {});
70
+ }
71
+ return taken.get(key);
72
+ };
73
+
74
+ /** Registers (once) a component for the target and returns its pointer segments. */
75
+ const componentFor = (kind, target, container) => {
76
+ const targetKey = `${target.location}${encodePointer(target.pointer)}`;
77
+ if (named.has(targetKey)) return named.get(targetKey);
78
+ const names = takenIn(container);
79
+ const base = nameFor(target.location, target.pointer);
80
+ let name = base;
81
+ for (let n = 2; names.has(name); n++) name = `${base}-${n}`;
82
+ names.set(name, targetKey);
83
+ const segments = [...container, name];
84
+ named.set(targetKey, segments);
85
+ added.push({ kind, name, from: target.location });
86
+ const file = files.get(target.location);
87
+ const byName = components.get(container.join("/"));
88
+ byName[name] = undefined; // takes its place now, ahead of the components its body adds
89
+ byName[name] = rewrite(
90
+ valueAt(file.value, target.pointer),
91
+ target.location,
92
+ kind,
93
+ new Set([targetKey]),
94
+ target.pointer,
95
+ );
96
+ return segments;
97
+ };
98
+
99
+ /**
100
+ * A copy of `node` (which lives in the file at `location`) with its $refs rewritten.
101
+ * `kind` is what the node is (undefined when unknown); `chain` holds the targets being inlined, so a
102
+ * cycle through inlining stops.
103
+ */
104
+ const rewrite = (node, location, kind, chain, pointer = []) => {
105
+ if (Array.isArray(node))
106
+ return node.map((item, i) => rewrite(item, location, kind, chain, [...pointer, String(i)]));
107
+ if (!isObject(node)) return node;
108
+
109
+ if (typeof node.$ref === "string") {
110
+ const target = resolveRef(location, node.$ref);
111
+ if (target.location === entry) return { ...node, $ref: encodePointer(target.pointer) };
112
+ const file = files.get(target.location);
113
+ if (!file) return { ...node }; // remote, not fetched: stays as written
114
+ const problem = file.error
115
+ ? `$ref "${node.$ref}": can't read ${target.location} (${file.error})`
116
+ : valueAt(file.value, target.pointer) === undefined
117
+ ? `$ref "${node.$ref}" points to nothing`
118
+ : undefined;
119
+ if (problem) {
120
+ problems.push({ location, pointer: [...pointer, "$ref"], message: problem });
121
+ return { ...node };
122
+ }
123
+ const container = kind && containerFor(kind, versions);
124
+ if (container) {
125
+ const { $ref, ...siblings } = node; // oxlint-disable-line no-unused-vars -- drops $ref
126
+ return { $ref: encodePointer(componentFor(kind, target, container)), ...siblings };
127
+ }
128
+ const targetKey = `${target.location}${encodePointer(target.pointer)}`;
129
+ if (chain.has(targetKey)) {
130
+ problems.push({
131
+ location,
132
+ pointer: [...pointer, "$ref"],
133
+ message: `$ref "${node.$ref}" is part of a cycle that can't be inlined (no component kind for it here)`,
134
+ });
135
+ return { ...node };
136
+ }
137
+ inlined++;
138
+ return rewrite(
139
+ valueAt(file.value, target.pointer),
140
+ target.location,
141
+ kind,
142
+ new Set([...chain, targetKey]),
143
+ target.pointer,
144
+ );
145
+ }
146
+
147
+ const out = {};
148
+ for (const [key, child] of Object.entries(node)) {
149
+ const childPointer = [...pointer, key];
150
+ const shape = childKind(kind, key, v2);
151
+ if (!shape) {
152
+ out[key] = rewrite(child, location, undefined, chain, childPointer);
153
+ } else if (shape[0] === "one") {
154
+ out[key] = rewrite(child, location, shape[1], chain, childPointer);
155
+ } else if (shape[0] === "list") {
156
+ out[key] = Array.isArray(child)
157
+ ? child.map((item, i) =>
158
+ rewrite(item, location, shape[1], chain, [...childPointer, String(i)]),
159
+ )
160
+ : rewrite(child, location, undefined, chain, childPointer);
161
+ } else {
162
+ out[key] = isObject(child)
163
+ ? Object.fromEntries(
164
+ Object.entries(child).map(([name, item]) => [
165
+ name,
166
+ rewrite(item, location, shape[1], chain, [...childPointer, name]),
167
+ ]),
168
+ )
169
+ : rewrite(child, location, undefined, chain, childPointer);
170
+ }
171
+ }
172
+ return out;
173
+ };
174
+
175
+ const value = rewrite(root, entry, "root", new Set());
176
+
177
+ // Merge the new components in, after the entry's own ones.
178
+ for (const [key, byName] of components) {
179
+ if (!Object.keys(byName).length) continue;
180
+ const container = key.split("/");
181
+ let node = value;
182
+ for (const segment of container.slice(0, -1)) node = node[segment] ??= {};
183
+ const last = container.at(-1);
184
+ node[last] = { ...(isObject(node[last]) ? node[last] : {}), ...byName };
185
+ }
186
+ return { value, problems, added, inlined };
187
+ }
@@ -0,0 +1,67 @@
1
+ import { encodePointer, resolveRef, valueAt } from "../validate/bundle.js";
2
+
3
+ /*
4
+ * Inlines every $ref of a spec, across files and within the entry file, so the output has none. A
5
+ * $ref that leads back to a node being inlined is a cycle: it can't be written out, so dereferencing
6
+ * stops with a CycleError naming the chain. (`toComponents` handles cycles, since they stay $refs.)
7
+ */
8
+
9
+ /** @typedef {import("../validate/bundle.js").SpecFile} SpecFile */
10
+
11
+ export class CycleError extends Error {
12
+ /** @param {{ location: string, pointer: string[] }[]} chain the $ref targets, from the first to the one that repeats */
13
+ constructor(chain) {
14
+ super("Recursive $ref can't be inlined");
15
+ this.chain = chain;
16
+ }
17
+ }
18
+
19
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
20
+
21
+ /**
22
+ * The entry file of `files` with every $ref replaced by what it points to. Sibling keys of a $ref
23
+ * (a 3.1 `description`, say) are kept over the target's.
24
+ * @param {{ entry: string, files: Map<string, SpecFile> }} loaded
25
+ * @returns {{ value: unknown, problems: { location: string, pointer: string[], message: string }[] }}
26
+ */
27
+ export function dereference({ entry, files }) {
28
+ const problems = [];
29
+
30
+ const walk = (node, location, chain, pointer) => {
31
+ if (Array.isArray(node))
32
+ return node.map((item, i) => walk(item, location, chain, [...pointer, String(i)]));
33
+ if (!isObject(node)) return node;
34
+
35
+ if (typeof node.$ref === "string") {
36
+ const target = resolveRef(location, node.$ref);
37
+ const file = files.get(target.location);
38
+ const { $ref, ...siblings } = node; // oxlint-disable-line no-unused-vars -- drops $ref
39
+ if (!file) return { ...node }; // remote, not fetched: stays as written
40
+ const value = file.error ? undefined : valueAt(file.value, target.pointer);
41
+ if (value === undefined) {
42
+ problems.push({
43
+ location,
44
+ pointer: [...pointer, "$ref"],
45
+ message: file.error
46
+ ? `$ref "${node.$ref}": can't read ${target.location} (${file.error})`
47
+ : `$ref "${node.$ref}" points to nothing`,
48
+ });
49
+ return { ...node };
50
+ }
51
+ const key = `${target.location}${encodePointer(target.pointer)}`;
52
+ const seen = chain.findIndex((link) => link.key === key);
53
+ if (seen >= 0) throw new CycleError([...chain.slice(seen), { key, ...target }]);
54
+ const resolved = walk(value, target.location, [...chain, { key, ...target }], target.pointer);
55
+ return isObject(resolved) && Object.keys(siblings).length
56
+ ? { ...resolved, ...siblings }
57
+ : resolved;
58
+ }
59
+
60
+ const out = {};
61
+ for (const [key, child] of Object.entries(node))
62
+ out[key] = walk(child, location, chain, [...pointer, key]);
63
+ return out;
64
+ };
65
+
66
+ return { value: walk(files.get(entry).value, entry, [], []), problems };
67
+ }
@@ -0,0 +1,20 @@
1
+ import path from "node:path";
2
+ import { stringify } from "yaml";
3
+
4
+ /*
5
+ * The bundled document as text. YAML keeps the keys in the order the spec had them; no anchors or
6
+ * aliases are written even where the same object appears twice (tools that read OpenAPI rarely take
7
+ * them). JSON is indented with two spaces.
8
+ */
9
+
10
+ /** "yaml" or "json": from --format, else from the output file's extension, else yaml. */
11
+ export function formatFor(format, output) {
12
+ if (format) return format;
13
+ return output && path.extname(output).toLowerCase() === ".json" ? "json" : "yaml";
14
+ }
15
+
16
+ /** @param {unknown} value @param {"yaml" | "json"} format */
17
+ export function serialize(value, format) {
18
+ if (format === "json") return `${JSON.stringify(value, null, 2)}\n`;
19
+ return stringify(value, { aliasDuplicateObjects: false, lineWidth: 0 });
20
+ }
@@ -0,0 +1,59 @@
1
+ import path from "node:path";
2
+ import { loadPortal } from "../lib/engines.js";
3
+ import { ProblemError } from "../lib/errors.js";
4
+ import { icon, info, warn } from "../lib/output.js";
5
+
6
+ export default {
7
+ name: "build",
8
+ usage: "build [dir]",
9
+ summary: "Pre-renders the static developer portal into dist/ (SSG)",
10
+ description:
11
+ "Builds the portal in dir (default: current folder). With sign-in configured, the output is split\ninto public/ and protected/; serve it with `rapidoc serve`.",
12
+ positionals: { name: "dir", max: 1 },
13
+ options: {
14
+ "out-dir": {
15
+ type: "string",
16
+ value: "path",
17
+ default: "dist",
18
+ description: "Output folder, relative to the portal folder",
19
+ },
20
+ debug: {
21
+ type: "boolean",
22
+ description:
23
+ "Keep the temporary Astro workspace and print its path (for debugging the engine)",
24
+ },
25
+ },
26
+ examples: ["rapidoc build", "rapidoc build ./my-portal", "rapidoc build --out-dir public"],
27
+
28
+ async run({ values, positionals }) {
29
+ const targetDir = path.resolve(positionals[0] || ".");
30
+ info(`\n${icon("🚀")}Building RapiDoc Portal in: ${targetDir}`);
31
+ info(` Engine: Astro + Starlight`);
32
+
33
+ const { buildPortal } = await loadPortal("build");
34
+ let result;
35
+ try {
36
+ result = await buildPortal(targetDir, {
37
+ outDir: values["out-dir"],
38
+ keepWorkspace: values.debug,
39
+ });
40
+ } catch (err) {
41
+ throw new ProblemError(`Build failed: ${err.message}`);
42
+ }
43
+
44
+ info(`\n${icon("✨")}Astro build completed successfully in ${result.durationMs}ms!`);
45
+ info(` • APIs compiled: ${result.apisCount}`);
46
+ info(` • Output folder: ${result.outDir}`);
47
+ if (result.workspaceDir) info(` • Workspace (kept): ${result.workspaceDir}`);
48
+ if (result.access) {
49
+ const { protectedPages, zones, warnings } = result.access;
50
+ info(` • Protected: ${protectedPages} page(s) in ${zones.length} zone(s)`);
51
+ for (const warning of warnings) warn(warning, " ");
52
+ const outRel = path.relative(process.cwd(), result.outDir) || ".";
53
+ info(
54
+ `\n Serve it with \`rapidoc serve ${outRel}\`. ${outRel}/public alone is safe to host anywhere but has no protected content.`,
55
+ );
56
+ }
57
+ info("");
58
+ },
59
+ };
@@ -0,0 +1,187 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { loadPortal } from "../lib/engines.js";
4
+ import { ProblemError, UsageError } from "../lib/errors.js";
5
+ import { error, icon, info, setQuiet, success, warn } from "../lib/output.js";
6
+
7
+ /*
8
+ * rapidoc bundle <spec>: one file from a spec split over several. By default every $ref to another file
9
+ * becomes a component (#/components/schemas/Order; #/definitions/Order in Swagger 2.0) and in-file $refs
10
+ * stay; --dereference inlines everything instead (and fails on a recursive schema). The result is
11
+ * validated before it's written, unless --no-validate.
12
+ */
13
+
14
+ const isUrl = (target) => /^https?:\/\//i.test(target);
15
+ /** A URL as is; a path relative to the current folder, or absolute when it's outside it. */
16
+ function displayPath(location) {
17
+ if (isUrl(location)) return location;
18
+ const relative = path.relative(process.cwd(), location);
19
+ return relative.startsWith("..") ? location : relative || ".";
20
+ }
21
+
22
+ /** The spec of the API `id` in the portal config of the current folder. */
23
+ async function specOfApi(id) {
24
+ const portal = await loadPortal("bundle --api");
25
+ let config;
26
+ try {
27
+ ({ config } = await portal.loadConfig(process.cwd()));
28
+ } catch (err) {
29
+ throw new ProblemError(err.message);
30
+ }
31
+ const api = (config.apis ?? []).find((entry) => entry.id === id);
32
+ if (!api) {
33
+ const ids = (config.apis ?? []).map((entry) => entry.id).join(", ") || "none";
34
+ throw new ProblemError(`No API "${id}" in rapidoc.config.* (APIs: ${ids})`);
35
+ }
36
+ const [version] = api.versions;
37
+ return version.isRemote ? version.spec : version.fullPath;
38
+ }
39
+
40
+ export default {
41
+ name: "bundle",
42
+ usage: "bundle <spec>",
43
+ summary: "Joins a spec split over several files into one (other-file $refs become components)",
44
+ description:
45
+ "Loads the spec and every file its $refs reach, and writes one document: a $ref to another file\nbecomes a component with a copy of what it pointed to, in-file $refs stay. --dereference inlines\nevery $ref instead. The result is validated before it's written.",
46
+ positionals: { name: "spec", max: 1 },
47
+ options: {
48
+ output: {
49
+ type: "string",
50
+ short: "o",
51
+ value: "file",
52
+ description: "Write here (.json or .yaml by its extension) instead of stdout",
53
+ },
54
+ format: {
55
+ type: "string",
56
+ value: "format",
57
+ choices: ["yaml", "json"],
58
+ description: "Output format (default: by the output file's extension, else yaml)",
59
+ },
60
+ dereference: {
61
+ type: "boolean",
62
+ description: "Inline every $ref, in-file ones too (fails on a recursive schema)",
63
+ },
64
+ validate: {
65
+ type: "boolean",
66
+ negatable: true,
67
+ default: true,
68
+ description: "Skip checking the result against the OpenAPI Specification before writing it",
69
+ },
70
+ remote: {
71
+ type: "boolean",
72
+ description: "Also fetch remote $refs (left as they are by default)",
73
+ },
74
+ api: {
75
+ type: "string",
76
+ value: "id",
77
+ description: "Bundle the spec of this API from rapidoc.config.* instead of a file",
78
+ },
79
+ },
80
+ examples: [
81
+ "rapidoc bundle openapi.yaml -o dist/openapi.json",
82
+ "rapidoc bundle openapi.yaml --dereference > flat.yaml",
83
+ "rapidoc bundle --api orders -o dist/orders.yaml",
84
+ ],
85
+
86
+ async run({ values, positionals }) {
87
+ const [target] = positionals;
88
+ if (target && values.api)
89
+ throw new UsageError("Give a spec or --api <id>, not both", { command: "bundle" });
90
+ if (!target && !values.api)
91
+ throw new UsageError("rapidoc bundle needs a spec: rapidoc bundle <spec>", {
92
+ command: "bundle",
93
+ });
94
+ // Without -o the document goes to stdout: nothing else may.
95
+ if (!values.output) setQuiet(true);
96
+
97
+ const { loadFiles, position, SpecSyntaxError } = await import("../validate/bundle.js");
98
+ const { toComponents } = await import("../bundle/components.js");
99
+ const { dereference, CycleError } = await import("../bundle/dereference.js");
100
+ const { formatFor, serialize } = await import("../bundle/write.js");
101
+
102
+ let entry = values.api ? await specOfApi(values.api) : target;
103
+ if (!isUrl(entry)) {
104
+ entry = path.resolve(entry);
105
+ if (!fs.existsSync(entry) || !fs.statSync(entry).isFile())
106
+ throw new ProblemError(`File not found: ${entry}`);
107
+ }
108
+
109
+ let loaded;
110
+ try {
111
+ loaded = await loadFiles(entry, { remote: values.remote });
112
+ } catch (err) {
113
+ if (err instanceof SpecSyntaxError)
114
+ throw new ProblemError(
115
+ `${displayPath(err.location)}:${err.line}:${err.column} ${err.message}`,
116
+ );
117
+ throw err;
118
+ }
119
+
120
+ let result;
121
+ try {
122
+ result = values.dereference ? dereference(loaded) : toComponents(loaded);
123
+ } catch (err) {
124
+ if (err instanceof CycleError) {
125
+ const { encodePointer } = await import("../validate/bundle.js");
126
+ const chain = err.chain
127
+ .map((link) => `${displayPath(link.location)}${encodePointer(link.pointer)}`)
128
+ .join("\n → ");
129
+ throw new ProblemError(
130
+ `${err.message}:\n ${chain}\n (without --dereference, cycles stay $refs)`,
131
+ );
132
+ }
133
+ throw err;
134
+ }
135
+ if (result.problems.length) {
136
+ error(`${result.problems.length} broken $ref(s):`);
137
+ for (const problem of result.problems) {
138
+ const { line, column } = position(loaded.files.get(problem.location), problem.pointer);
139
+ process.stderr.write(
140
+ ` ${displayPath(problem.location)}:${line}:${column} ${problem.message}\n`,
141
+ );
142
+ }
143
+ throw new ProblemError("Nothing written: fix the $refs above first.");
144
+ }
145
+ for (const skipped of loaded.skipped)
146
+ warn(`$ref to ${skipped} left as is (remote; use --remote to fetch it)`);
147
+
148
+ if (values.validate) {
149
+ const { validate } = await import("@scalar/openapi-validator");
150
+ const { errors = [] } = await validate(result.value, { checkPathParameters: false });
151
+ if (errors.length) {
152
+ error(`The bundle is not valid OpenAPI (${errors.length} error(s)):`);
153
+ for (const problem of errors) {
154
+ const at = Array.isArray(problem.path)
155
+ ? `#/${problem.path.join("/")}`
156
+ : `#${String(problem.path ?? "").replace(/^#/, "")}`;
157
+ process.stderr.write(` ${at} ${problem.message}\n`);
158
+ }
159
+ throw new ProblemError(
160
+ "Nothing written. Run rapidoc validate on the source for file:line:col, or pass --no-validate.",
161
+ );
162
+ }
163
+ }
164
+
165
+ const format = formatFor(values.format, values.output);
166
+ const text = serialize(result.value, format);
167
+ if (!values.output) {
168
+ process.stdout.write(text);
169
+ return;
170
+ }
171
+ const output = path.resolve(values.output);
172
+ fs.mkdirSync(path.dirname(output), { recursive: true });
173
+ fs.writeFileSync(output, text, "utf8");
174
+
175
+ const files = loaded.files.size;
176
+ const size = (Buffer.byteLength(text) / 1024).toFixed(1);
177
+ info(`\n${icon("📦")}Bundled ${displayPath(entry)} → ${displayPath(output)} (${size} KB)`);
178
+ if (values.dereference) {
179
+ info(` • ${files} file(s) merged, every $ref inlined`);
180
+ } else {
181
+ info(` • ${files} file(s) merged, ${result.added.length} component(s) added`);
182
+ if (result.inlined)
183
+ info(` • ${result.inlined} $ref(s) inlined (no component kind for them)`);
184
+ }
185
+ success(`Valid ${format.toUpperCase()}${values.validate ? ", valid OpenAPI" : ""}.\n`, " ");
186
+ },
187
+ };