@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,24 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-operationId-unique",
4
+ description:
5
+ "No two operations share an operationId: they would share a page URL and an MCP tool name.",
6
+ default: "error",
7
+ on: ["document"],
8
+ check: (_doc, { operations }) => {
9
+ const seen = new Map();
10
+ const findings = [];
11
+ for (const op of operations) {
12
+ const id = op.node.operationId;
13
+ if (typeof id !== "string" || !id) continue;
14
+ const first = seen.get(id);
15
+ if (first)
16
+ findings.push({
17
+ pointer: [...op.pointer, "operationId"],
18
+ message: `operationId "${id}" is also used by ${first.method.toUpperCase()} ${first.path}`,
19
+ });
20
+ else seen.set(id, op);
21
+ }
22
+ return findings;
23
+ },
24
+ };
@@ -0,0 +1,18 @@
1
+ const SAFE = /^[A-Za-z0-9._-]+$/;
2
+
3
+ /** @type {import("../types.js").Rule} */
4
+ export default {
5
+ name: "operation-operationId-url-safe",
6
+ description: "operationIds use letters, digits, '_', '-' and '.' only: they appear in page URLs.",
7
+ default: "warn",
8
+ on: ["operation"],
9
+ check: (op, { pointer }) =>
10
+ typeof op.operationId !== "string" || !op.operationId || SAFE.test(op.operationId)
11
+ ? []
12
+ : [
13
+ {
14
+ pointer: [...pointer, "operationId"],
15
+ message: `operationId "${op.operationId}" has characters other than letters, digits, '_', '-' and '.'`,
16
+ },
17
+ ],
18
+ };
@@ -0,0 +1,12 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-operationId",
4
+ description:
5
+ "Every operation has an operationId: the portal builds stable page URLs from it, and MCP tool names.",
6
+ default: "warn",
7
+ on: ["operation"],
8
+ check: (op, { pointer, method, path }) =>
9
+ typeof op.operationId === "string" && op.operationId.trim()
10
+ ? []
11
+ : [{ pointer, message: `${method.toUpperCase()} ${path} has no operationId` }],
12
+ };
@@ -0,0 +1,12 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-summary",
4
+ description:
5
+ "Every operation has a summary: it is the sidebar label of the operation and the title of its MCP tool.",
6
+ default: "warn",
7
+ on: ["operation"],
8
+ check: (op, { pointer, method, path }) =>
9
+ typeof op.summary === "string" && op.summary.trim()
10
+ ? []
11
+ : [{ pointer, message: `${method.toUpperCase()} ${path} has no summary` }],
12
+ };
@@ -0,0 +1,22 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "operation-tag-defined",
4
+ description:
5
+ "Tags used by operations are declared in the top-level tags list: that is where the sidebar group's description and order come from.",
6
+ default: "warn",
7
+ on: ["operation"],
8
+ check: (op, { pointer, doc }) => {
9
+ if (!Array.isArray(op.tags)) return [];
10
+ const declared = new Set((Array.isArray(doc.tags) ? doc.tags : []).map((tag) => tag?.name));
11
+ return op.tags
12
+ .map((tag, i) =>
13
+ declared.has(tag)
14
+ ? null
15
+ : {
16
+ pointer: [...pointer, "tags", String(i)],
17
+ message: `Tag "${tag}" is not in the top-level tags list`,
18
+ },
19
+ )
20
+ .filter(Boolean);
21
+ },
22
+ };
@@ -0,0 +1,16 @@
1
+ const KEBAB = /^[a-z0-9.]+(-[a-z0-9.]+)*$/;
2
+
3
+ /** @type {import("../types.js").Rule} */
4
+ export default {
5
+ name: "path-kebab-case",
6
+ description:
7
+ "Path segments other than parameters are kebab-case (/order-items, not /orderItems).",
8
+ default: "off",
9
+ on: ["pathItem"],
10
+ check: (_item, { pointer, path }) => {
11
+ const bad = (path ?? "")
12
+ .split("/")
13
+ .filter((segment) => segment && !/^\{.*\}$/.test(segment) && !KEBAB.test(segment));
14
+ return bad.length ? [{ pointer, message: `${path}: "${bad[0]}" is not kebab-case` }] : [];
15
+ },
16
+ };
@@ -0,0 +1,23 @@
1
+ const WRITES = new Set(["post", "put", "patch", "delete"]);
2
+
3
+ /** @type {import("../types.js").Rule} */
4
+ export default {
5
+ name: "security-defined",
6
+ description:
7
+ "Write operations (POST, PUT, PATCH, DELETE) have a security requirement, their own or the document's: Try and the mock server need it, and MCP marks them as consequential. An explicit `security: []` opts out.",
8
+ default: "warn",
9
+ on: ["operation"],
10
+ check: (op, { pointer, method, path, doc }) => {
11
+ if (!WRITES.has(method)) return [];
12
+ const own = Array.isArray(op.security);
13
+ const global = Array.isArray(doc.security) && doc.security.length > 0;
14
+ return own || global
15
+ ? []
16
+ : [
17
+ {
18
+ pointer,
19
+ message: `${method.toUpperCase()} ${path} has no security requirement (and the document has none)`,
20
+ },
21
+ ];
22
+ },
23
+ };
@@ -0,0 +1,28 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "security-scheme-defined",
4
+ description:
5
+ "Every security scheme a requirement names is declared (components.securitySchemes, or securityDefinitions): Try's authentication panel is built from the declarations.",
6
+ default: "error",
7
+ on: ["document"],
8
+ check: (doc, { v2, operations }) => {
9
+ const declared = new Set(
10
+ Object.keys((v2 ? doc.securityDefinitions : doc.components?.securitySchemes) ?? {}),
11
+ );
12
+ const findings = [];
13
+ const checkList = (list, pointer) => {
14
+ if (!Array.isArray(list)) return;
15
+ list.forEach((requirement, i) => {
16
+ for (const name of Object.keys(requirement ?? {}))
17
+ if (!declared.has(name))
18
+ findings.push({
19
+ pointer: [...pointer, String(i), name],
20
+ message: `Security scheme "${name}" is not declared`,
21
+ });
22
+ });
23
+ };
24
+ checkList(doc.security, ["security"]);
25
+ for (const op of operations) checkList(op.node.security, [...op.pointer, "security"]);
26
+ return findings;
27
+ },
28
+ };
@@ -0,0 +1,11 @@
1
+ /** @type {import("../types.js").Rule} */
2
+ export default {
3
+ name: "tag-description",
4
+ description: "Every top-level tag has a description: it introduces the group on the API page.",
5
+ default: "off",
6
+ on: ["tag"],
7
+ check: (tag, { pointer }) =>
8
+ typeof tag.description === "string" && tag.description.trim()
9
+ ? []
10
+ : [{ pointer, message: `Tag "${tag.name}" has no description` }],
11
+ };
@@ -0,0 +1,50 @@
1
+ import { bundleSpec, locate, position, SpecSyntaxError } from "../validate/bundle.js";
2
+ import { checkSpec } from "../validate/check.js";
3
+ import { RULES } from "./rules/index.js";
4
+ import { traverse } from "./traverse.js";
5
+
6
+ /*
7
+ * Lints one spec: validate's strict check first (an invalid spec is not linted further, so one CI step
8
+ * covers both), then every rule whose severity isn't off, over one traversal. Each finding comes back
9
+ * as a problem of validate's shape, with the file, line and column it traces back to.
10
+ */
11
+
12
+ /** @import { Severity } from "./types.js" */
13
+
14
+ /**
15
+ * @param {string} location file path or URL
16
+ * @param {{ remote?: boolean, severities: Record<string, Severity> }} options
17
+ * @returns {Promise<{ location, problems, skipped: string[], linted: boolean }>}
18
+ */
19
+ export async function lintSpec(location, { remote = false, severities }) {
20
+ let bundle;
21
+ try {
22
+ bundle = await bundleSpec(location, { remote });
23
+ } catch (err) {
24
+ if (!(err instanceof SpecSyntaxError)) throw err;
25
+ const checked = await checkSpec(location, { remote }); // reports the syntax error
26
+ return { ...checked, linted: false };
27
+ }
28
+ const checked = await checkSpec(location, { remote, bundle });
29
+ if (checked.problems.length) return { ...checked, linted: false };
30
+
31
+ const active = RULES.filter((rule) => severities[rule.name] !== "off");
32
+ const problems = traverse(bundle.value, active).map((finding) => {
33
+ const at = locate(bundle, finding.pointer);
34
+ const { line, column } = position(bundle.files.get(at.location), at.pointer);
35
+ return {
36
+ severity: severities[finding.rule] === "error" ? "error" : "warning",
37
+ rule: finding.rule,
38
+ message: finding.message,
39
+ location: at.location,
40
+ pointer: at.pointer,
41
+ line,
42
+ column,
43
+ };
44
+ });
45
+ // In file order, so the output reads top to bottom.
46
+ problems.sort(
47
+ (a, b) => a.location.localeCompare(b.location) || a.line - b.line || a.column - b.column,
48
+ );
49
+ return { location, problems, skipped: bundle.skipped, linted: true };
50
+ }
@@ -0,0 +1,114 @@
1
+ import { childKind, METHODS } from "../lib/openapi-shape.js";
2
+ import { decodePointer, valueAt } from "../validate/bundle.js";
3
+
4
+ /*
5
+ * One walk of the document that calls every rule on the nodes of the kinds it asked for. A $ref is not
6
+ * descended into (its target is walked where it lives, under components); rules that need the target
7
+ * call context.resolve.
8
+ */
9
+
10
+ /** @import { Finding, LintContext, Operation, Rule } from "./types.js" */
11
+
12
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13
+
14
+ /** Follows `#/...` $refs in `doc`, up to 10 hops; anything else comes back as is. */
15
+ export const resolver = (doc) => (node) => {
16
+ for (let hops = 0; isObject(node) && typeof node.$ref === "string" && hops < 10; hops++) {
17
+ if (!node.$ref.startsWith("#")) return node;
18
+ const target = valueAt(doc, decodePointer(node.$ref));
19
+ if (target === undefined) return node;
20
+ node = target;
21
+ }
22
+ return node;
23
+ };
24
+
25
+ /** Every operation of the document, with its route and method. @returns {Operation[]} */
26
+ export function operationsOf(doc, resolve) {
27
+ const operations = [];
28
+ for (const [path, rawItem] of Object.entries(isObject(doc.paths) ? doc.paths : {})) {
29
+ const item = resolve(rawItem);
30
+ if (!isObject(item)) continue;
31
+ for (const method of METHODS)
32
+ if (isObject(item[method]))
33
+ operations.push({ node: item[method], pointer: ["paths", path, method], path, method });
34
+ }
35
+ return operations;
36
+ }
37
+
38
+ /**
39
+ * Runs `rules` over `doc`; returns each finding with the rule that made it.
40
+ * @param {object} doc
41
+ * @param {Rule[]} rules
42
+ * @returns {(Finding & { rule: string })[]}
43
+ */
44
+ export function traverse(doc, rules) {
45
+ const v2 = typeof doc.swagger === "string";
46
+ const resolve = resolver(doc);
47
+ const operations = operationsOf(doc, resolve);
48
+ const findings = [];
49
+
50
+ /** kind → rules wanting it */
51
+ const byKind = new Map();
52
+ for (const rule of rules)
53
+ for (const kind of rule.on) (byKind.get(kind) ?? byKind.set(kind, []).get(kind)).push(rule);
54
+
55
+ const visit = (kind, node, pointer, parents, extra) => {
56
+ const wanting = byKind.get(kind);
57
+ if (!wanting) return;
58
+ /** @type {LintContext} */
59
+ const context = { doc, v2, pointer, parents, operations, resolve, ...extra };
60
+ for (const rule of wanting)
61
+ for (const finding of rule.check(node, context))
62
+ findings.push({ ...finding, rule: rule.name });
63
+ };
64
+
65
+ const walk = (kind, node, pointer, parents, extra) => {
66
+ if (!isObject(node)) return;
67
+ visit(kind, node, pointer, parents, extra);
68
+ if (typeof node.$ref === "string") return;
69
+ const below = [...parents, kind];
70
+ for (const [key, child] of Object.entries(node)) {
71
+ const shape = childKind(kind, key, v2);
72
+ if (!shape) continue;
73
+ const childPointer = [...pointer, key];
74
+ const [arity, childKindName] = shape;
75
+ const childExtra =
76
+ kind === "pathItem" && childKindName === "operation" ? { ...extra, method: key } : extra;
77
+ if (arity === "one") walk(childKindName, child, childPointer, below, childExtra);
78
+ else if (arity === "list" && Array.isArray(child))
79
+ child.forEach((item, i) =>
80
+ walk(childKindName, item, [...childPointer, String(i)], below, childExtra),
81
+ );
82
+ else if (arity === "map" && isObject(child))
83
+ for (const [name, item] of Object.entries(child))
84
+ walk(
85
+ childKindName,
86
+ item,
87
+ [...childPointer, name],
88
+ below,
89
+ childKindName === "pathItem" && kind === "root" ? { ...extra, path: name } : childExtra,
90
+ );
91
+ }
92
+ };
93
+
94
+ visit("document", doc, [], [], {});
95
+ if (isObject(doc.info)) visit("info", doc.info, ["info"], ["root"], {});
96
+ if (Array.isArray(doc.servers))
97
+ doc.servers.forEach((server, i) =>
98
+ visit("server", server, ["servers", String(i)], ["root"], {}),
99
+ );
100
+ if (Array.isArray(doc.tags))
101
+ doc.tags.forEach((tag, i) => visit("tag", tag, ["tags", String(i)], ["root"], {}));
102
+ const schemes = v2 ? doc.securityDefinitions : doc.components?.securitySchemes;
103
+ if (isObject(schemes))
104
+ for (const [name, scheme] of Object.entries(schemes))
105
+ visit(
106
+ "securityScheme",
107
+ scheme,
108
+ v2 ? ["securityDefinitions", name] : ["components", "securitySchemes", name],
109
+ ["root"],
110
+ {},
111
+ );
112
+ walk("root", doc, [], [], {});
113
+ return findings;
114
+ }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * The shapes `rapidoc lint` is built from. Rules are small pure functions: given a node of a kind they
3
+ * asked for and the context, they return findings; the runner adds file, line and column.
4
+ */
5
+
6
+ /**
7
+ * @typedef {"error" | "warn" | "off"} Severity
8
+ */
9
+
10
+ /**
11
+ * @typedef {object} Finding
12
+ * @property {string[]} pointer JSON pointer segments of what's wrong, in the linted document
13
+ * @property {string} message
14
+ */
15
+
16
+ /**
17
+ * @typedef {object} Operation
18
+ * @property {object} node
19
+ * @property {string[]} pointer
20
+ * @property {string} path the route, "/orders/{id}"
21
+ * @property {string} method lower case
22
+ */
23
+
24
+ /**
25
+ * @typedef {object} LintContext
26
+ * @property {object} doc the whole document (other-file $refs inlined, in-file ones kept)
27
+ * @property {boolean} v2 Swagger 2.0
28
+ * @property {string[]} pointer where the node is
29
+ * @property {string[]} parents the kinds of the node's ancestors, nearest last
30
+ * @property {string} [path] the route, inside a path item
31
+ * @property {string} [method] the method, inside an operation
32
+ * @property {Operation[]} operations every operation of the document
33
+ * @property {(node: unknown) => unknown} resolve follows in-document $refs (up to 10 hops)
34
+ */
35
+
36
+ /**
37
+ * @typedef {object} Rule
38
+ * @property {string} name kebab-case, as in --rule and the config
39
+ * @property {string} description one sentence: what it checks and why the portal cares
40
+ * @property {Severity} default
41
+ * @property {string[]} on node kinds it wants (see lib/openapi-shape.js), plus "document",
42
+ * "info", "server", "tag" and "securityScheme"
43
+ * @property {(node: any, context: LintContext) => Finding[]} check
44
+ */
45
+
46
+ export {};
@@ -0,0 +1,238 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
4
+
5
+ /*
6
+ * Loads a spec and the files its $refs point to, keeping each file's YAML document for line and column
7
+ * numbers (JSON is YAML, so .json works the same), and builds the "bundle" that is validated:
8
+ *
9
+ * - $refs into other files (or other URLs) are replaced by what they point to, so that content is
10
+ * checked too;
11
+ * - $refs within the main file stay as they are: the validators check them as written, and recursive
12
+ * schemas (a $ref back to an ancestor) can't loop;
13
+ * - every copied object and array remembers the file and JSON pointer it came from (`origin`), so an
14
+ * error at a path in the bundle can be traced back to its file, line and column (`locate`).
15
+ */
16
+
17
+ export const isUrl = (location) => /^https?:\/\//i.test(location);
18
+
19
+ export const decodePointer = (pointer) =>
20
+ pointer
21
+ .replace(/^#/, "")
22
+ .split("/")
23
+ .slice(1)
24
+ .map((segment) => decodeURIComponent(segment.replace(/~1/g, "/").replace(/~0/g, "~")));
25
+
26
+ export const encodePointer = (segments) =>
27
+ `#${segments.map((segment) => `/${String(segment).replace(/~/g, "~0").replace(/\//g, "~1")}`).join("")}`;
28
+
29
+ /** Where `ref` (as written in the file at `from`) points: { location, pointer }. */
30
+ export function resolveRef(from, ref) {
31
+ const [target, fragment = ""] = ref.split("#");
32
+ let location = from;
33
+ if (isUrl(target)) location = new URL(target).href;
34
+ else if (target)
35
+ location = isUrl(from) ? new URL(target, from).href : path.resolve(path.dirname(from), target);
36
+ return { location, pointer: fragment ? decodePointer(`#${fragment}`) : [] };
37
+ }
38
+
39
+ export function valueAt(value, pointer) {
40
+ let node = value;
41
+ for (const segment of pointer) {
42
+ if (node === null || typeof node !== "object") return undefined;
43
+ node = node[segment];
44
+ }
45
+ return node;
46
+ }
47
+
48
+ async function readSource(location) {
49
+ if (!isUrl(location)) return fs.readFileSync(location, "utf8");
50
+ const response = await fetch(location);
51
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
52
+ return response.text();
53
+ }
54
+
55
+ export class SpecSyntaxError extends Error {
56
+ constructor(location, message, line, column) {
57
+ super(message);
58
+ Object.assign(this, { location, line, column });
59
+ }
60
+ }
61
+
62
+ async function parseFile(location) {
63
+ const text = await readSource(location);
64
+ const lineCounter = new LineCounter();
65
+ const doc = parseDocument(text, { lineCounter, prettyErrors: true, uniqueKeys: false });
66
+ if (doc.errors.length) {
67
+ const [first] = doc.errors;
68
+ const { line, col } = first.linePos?.[0] ?? { line: 1, col: 1 };
69
+ throw new SpecSyntaxError(location, first.message.split("\n")[0], line, col);
70
+ }
71
+ return { location, doc, lineCounter, value: doc.toJS({ maxAliasCount: -1 }) };
72
+ }
73
+
74
+ /** Every $ref string in a parsed value. */
75
+ function refsIn(value, found = []) {
76
+ if (Array.isArray(value)) for (const item of value) refsIn(item, found);
77
+ else if (value && typeof value === "object") {
78
+ if (typeof value.$ref === "string") found.push(value.$ref);
79
+ for (const child of Object.values(value)) refsIn(child, found);
80
+ }
81
+ return found;
82
+ }
83
+
84
+ /**
85
+ * @typedef {object} SpecFile
86
+ * @property {string} location file path or URL
87
+ * @property {import("yaml").Document} [doc] the parsed document (for positions)
88
+ * @property {LineCounter} [lineCounter]
89
+ * @property {unknown} [value] the document as plain data
90
+ * @property {string} [error] why the file couldn't be read (then no doc or value)
91
+ */
92
+
93
+ /**
94
+ * Loads `entry` and every file reachable through $refs (breadth first). Remote files are fetched only
95
+ * with `remote` (or when the entry itself is a URL); others are listed in `skipped` and stay $refs.
96
+ * A file that can't be read is kept with its `error`, so the $ref to it can be reported where it is.
97
+ * @returns {Promise<{ entry: string, files: Map<string, SpecFile>, skipped: string[] }>}
98
+ */
99
+ export async function loadFiles(entry, { remote = false } = {}) {
100
+ const allowRemote = remote || isUrl(entry);
101
+ const files = new Map([[entry, await parseFile(entry)]]);
102
+ const skipped = new Set();
103
+
104
+ const queue = [entry];
105
+ while (queue.length) {
106
+ const from = queue.shift();
107
+ for (const ref of refsIn(files.get(from).value)) {
108
+ const { location } = resolveRef(from, ref);
109
+ if (files.has(location)) continue;
110
+ if (isUrl(location) && !allowRemote) {
111
+ skipped.add(location);
112
+ continue;
113
+ }
114
+ try {
115
+ files.set(location, await parseFile(location));
116
+ queue.push(location);
117
+ } catch (err) {
118
+ if (err instanceof SpecSyntaxError) throw err;
119
+ files.set(location, { location, error: err.message });
120
+ }
121
+ }
122
+ }
123
+ return { entry, files, skipped: [...skipped] };
124
+ }
125
+
126
+ /**
127
+ * Loads `entry` and the files its $refs reach, then inlines every other-file $ref (in-file ones stay).
128
+ * Returns { entry, files: Map<location, file>, value, origin, problems, skipped }.
129
+ */
130
+ export async function bundleSpec(entry, { remote = false } = {}) {
131
+ const { files, skipped } = await loadFiles(entry, { remote });
132
+ const problems = [];
133
+
134
+ const origin = new WeakMap();
135
+ const copy = (node, location, pointer, chain) => {
136
+ if (Array.isArray(node)) {
137
+ const out = node.map((item, i) => copy(item, location, [...pointer, String(i)], chain));
138
+ origin.set(out, { location, pointer });
139
+ return out;
140
+ }
141
+ if (!node || typeof node !== "object") return node;
142
+
143
+ if (typeof node.$ref === "string") {
144
+ const target = resolveRef(location, node.$ref);
145
+ const refPointer = [...pointer, "$ref"];
146
+ if (target.location === entry) {
147
+ // Points into the main file: keep it as a $ref within the bundle.
148
+ if (valueAt(files.get(entry).value, target.pointer) === undefined)
149
+ problems.push({
150
+ location,
151
+ pointer: refPointer,
152
+ message: `$ref "${node.$ref}" points to nothing`,
153
+ });
154
+ const kept = { ...node, $ref: encodePointer(target.pointer) };
155
+ origin.set(kept, { location, pointer });
156
+ return kept;
157
+ }
158
+ const file = files.get(target.location);
159
+ if (!file) {
160
+ // A remote file that wasn't fetched (listed in `skipped`): the $ref stays as written.
161
+ const kept = { ...node };
162
+ origin.set(kept, { location, pointer });
163
+ return kept;
164
+ }
165
+ if (file.error) {
166
+ problems.push({
167
+ location,
168
+ pointer: refPointer,
169
+ message: `$ref "${node.$ref}": can't read ${target.location} (${file.error})`,
170
+ });
171
+ return {};
172
+ }
173
+ const key = `${target.location}${encodePointer(target.pointer)}`;
174
+ const value = valueAt(file.value, target.pointer);
175
+ if (value === undefined) {
176
+ problems.push({
177
+ location,
178
+ pointer: refPointer,
179
+ message: `$ref "${node.$ref}" points to nothing`,
180
+ });
181
+ return {};
182
+ }
183
+ // A $ref chain that comes back to itself across files: stop there.
184
+ if (chain.has(key)) return {};
185
+ return copy(value, target.location, target.pointer, new Set([...chain, key]));
186
+ }
187
+
188
+ const out = {};
189
+ for (const [key, child] of Object.entries(node))
190
+ out[key] = copy(child, location, [...pointer, key], chain);
191
+ origin.set(out, { location, pointer });
192
+ return out;
193
+ };
194
+
195
+ const value = copy(files.get(entry).value, entry, [], new Set());
196
+ return { entry, files, value, origin, problems, skipped };
197
+ }
198
+
199
+ /** The file and JSON pointer that a path in the bundle comes from. */
200
+ export function locate(bundle, segments) {
201
+ let node = bundle.value;
202
+ let best = bundle.origin.get(node);
203
+ let rest = [];
204
+ for (const segment of segments) {
205
+ node = node !== null && typeof node === "object" ? node[segment] : undefined;
206
+ const from = node !== null && typeof node === "object" ? bundle.origin.get(node) : undefined;
207
+ if (from) [best, rest] = [from, []];
208
+ else rest.push(segment);
209
+ }
210
+ return { location: best.location, pointer: [...best.pointer, ...rest] };
211
+ }
212
+
213
+ /**
214
+ * Line and column (1-based) of a JSON pointer in a loaded file: the key of the deepest property that
215
+ * exists along the pointer (a missing property points at its parent).
216
+ */
217
+ export function position(file, pointer) {
218
+ if (!file?.doc) return { line: 1, column: 1 };
219
+ let node = file.doc.contents;
220
+ let range = node?.range;
221
+ for (const segment of pointer) {
222
+ if (isMap(node)) {
223
+ const pair = node.items.find(
224
+ (item) => String(isScalar(item.key) ? item.key.value : item.key) === segment,
225
+ );
226
+ if (!pair) break;
227
+ range = pair.key?.range ?? pair.value?.range ?? range;
228
+ node = pair.value;
229
+ } else if (isSeq(node)) {
230
+ const item = node.items[Number(segment)];
231
+ if (!item) break;
232
+ range = item.range ?? range;
233
+ node = item;
234
+ } else break;
235
+ }
236
+ const { line, col } = file.lineCounter.linePos(range?.[0] ?? 0);
237
+ return { line, column: col };
238
+ }