@openmoca/moca-convert 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,134 @@
1
+ // `directory` adapter: a folder of Markdown files (optionally nested) becomes
2
+ // one content node per file, at the same path under content/. The folders
3
+ // become the package's structure (package spec §5.6), as the pdf and youtube
4
+ // adapters write theirs: a concept per folder and per file, parts by
5
+ // dct:hasPart, and each folder's order (by name) as an ordered collection.
6
+ // Each file's node is bound to its own concept, unless its frontmatter already
7
+ // has a `moca` block. --no-structure leaves structure.ttl out.
8
+ import { existsSync, statSync } from 'node:fs';
9
+ import { basename, extname, join } from 'node:path';
10
+ import { walkFiles } from '../walk.js';
11
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
12
+ import { buildManifest } from '../manifest.js';
13
+ import { UsageError } from '../target.js';
14
+ import { turtleString } from '../text.js';
15
+
16
+ export const name = 'directory';
17
+ export const DEFAULT_TYPE = 'Document';
18
+
19
+ // A folder's own page, whose title names the folder: OKF's index.md, or a README.
20
+ const FOLDER_PAGES = ['index.md', 'README.md', 'readme.md'];
21
+
22
+ /** @param {string} inputPath */
23
+ export function detect(inputPath) {
24
+ if (!existsSync(inputPath) || !statSync(inputPath).isDirectory()) return false;
25
+ return walkFiles(inputPath).some((f) => f.endsWith('.md'));
26
+ }
27
+
28
+ /**
29
+ * @param {{ inputPath: string, options: object }} ctx
30
+ * @returns {import('./index.js').PackageDraft}
31
+ */
32
+ export function convert({ inputPath, options }) {
33
+ const manifest = buildManifest(options);
34
+ const files = walkFiles(inputPath).filter((f) => f.endsWith('.md'));
35
+ if (files.length === 0) throw new UsageError(`No Markdown files found under ${inputPath}.`);
36
+ const type = options.type ?? DEFAULT_TYPE;
37
+ const withStructure = options.structure !== false;
38
+ const iri = (fragment) => `${manifest.id}#${fragment}`;
39
+ const warnings = [];
40
+ const titles = new Map();
41
+
42
+ const contentNodes = files.map((relPath) => {
43
+ const { data, content, raw } = readContentFile(join(inputPath, relPath));
44
+ const title = deriveTitle(data, content, basename(relPath, extname(relPath)));
45
+ titles.set(relPath, title);
46
+ let extra = {};
47
+ if (withStructure && !isFolderPage(relPath)) {
48
+ if (data.moca === undefined) {
49
+ extra = { moca: { concepts: [{ iri: iri(fileFragment(relPath)), role: 'primary' }] } };
50
+ } else {
51
+ warnings.push({
52
+ code: 'STRUCTURE_NOT_BOUND',
53
+ message: 'has its own moca block, so it is not bound to its concept in structure.ttl',
54
+ file: relPath,
55
+ });
56
+ }
57
+ }
58
+ return { path: `content/${relPath}`, body: ensureOkf(raw, data, { type, title }, extra) };
59
+ });
60
+
61
+ const result = { manifest, contentNodes, warnings };
62
+ if (withStructure) {
63
+ result.files = [{ path: 'structure.ttl', body: structure(manifest, files, titles, { iri, lang: options.language }) }];
64
+ }
65
+ return result;
66
+ }
67
+
68
+ /** A file's concept fragment: its path without .md. */
69
+ function fileFragment(relPath) {
70
+ return relPath.replace(/\.md$/, '');
71
+ }
72
+
73
+ function isFolderPage(relPath) {
74
+ return FOLDER_PAGES.includes(relPath.split('/').pop());
75
+ }
76
+
77
+ // Words that number a division of a document: "part-3-..." reads "Part 3: ...".
78
+ const NUMBERED = /^(part|chapter|section|schedule|module|unit|lesson|appendix|annex|article|volume) (\w+) (.+)$/i;
79
+
80
+ /**
81
+ * A folder's label: the title of its index.md or README, else its name without
82
+ * a leading order number, in sentence case ("011-resource-management" ->
83
+ * "Resource management"), with a numbered division read as one
84
+ * ("03-part-3-law-enforcement-processing" -> "Part 3: Law enforcement processing").
85
+ */
86
+ export function folderLabel(folder, titles) {
87
+ for (const page of FOLDER_PAGES) {
88
+ const title = titles.get(`${folder}/${page}`);
89
+ if (title) return title;
90
+ }
91
+ const last = folder.split('/').pop();
92
+ const words = last.replace(/^\d+[-_. ]+/, '').replace(/[-_]+/g, ' ').trim();
93
+ if (!words) return last;
94
+ const sentence = (s) => s[0].toUpperCase() + s.slice(1);
95
+ const numbered = NUMBERED.exec(words);
96
+ return numbered ? `${sentence(numbered[1].toLowerCase())} ${numbered[2].toUpperCase()}: ${sentence(numbered[3])}` : sentence(words);
97
+ }
98
+
99
+ /**
100
+ * The folders as structure: the package as a whole ("collection"), each
101
+ * folder and each file a concept, parts by dct:hasPart, and each container's
102
+ * children, folders and files together in name order, as an ordered collection.
103
+ */
104
+ function structure(manifest, files, titles, { iri, lang }) {
105
+ const label = (text) => `${turtleString(text)}${lang ? `@${lang}` : ''}`;
106
+ const ref = (fragment) => `<${iri(fragment)}>`;
107
+ const children = new Map([['', new Set()]]);
108
+ for (const file of files) {
109
+ if (isFolderPage(file)) continue;
110
+ const parts = file.split('/');
111
+ for (let i = 0; i < parts.length; i++) {
112
+ const parent = parts.slice(0, i).join('/');
113
+ const child = parts.slice(0, i + 1).join('/');
114
+ if (!children.has(parent)) children.set(parent, new Set());
115
+ children.get(parent).add(child);
116
+ }
117
+ }
118
+ const fragment = (path) => (path === '' ? 'collection' : path.endsWith('.md') ? fileFragment(path) : path);
119
+ const order = (path) => [...children.get(path)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
120
+ const blocks = ['@prefix skos: <http://www.w3.org/2004/02/skos/core#> .\n@prefix dct: <http://purl.org/dc/terms/> .'];
121
+ for (const container of [...children.keys()].sort()) {
122
+ const members = order(container).map((c) => ref(fragment(c)));
123
+ if (members.length === 0) continue;
124
+ const name = container === '' ? manifest.title : folderLabel(container, titles);
125
+ blocks.push(`${ref(fragment(container))} a skos:Concept ;\n skos:prefLabel ${label(name)} ;\n dct:hasPart ${members.join(',\n ')} .`);
126
+ blocks.push(
127
+ `${ref(`${fragment(container)}-order`)} a skos:OrderedCollection ;\n skos:prefLabel ${label(`${name} (folder order)`)} ;\n skos:memberList (\n ${members.join('\n ')}\n ) .`,
128
+ );
129
+ }
130
+ for (const file of files) {
131
+ if (!isFolderPage(file)) blocks.push(`${ref(fileFragment(file))} a skos:Concept ;\n skos:prefLabel ${label(titles.get(file))} .`);
132
+ }
133
+ return `${blocks.join('\n\n')}\n`;
134
+ }
@@ -0,0 +1,60 @@
1
+ // Adapter registry. Every adapter module exports `name`, `detect(inputPath)`,
2
+ // and `convert({ inputPath, options })`, which returns a PackageDraft or a
3
+ // promise of one. `detect`/`convert` never touch disk
4
+ // outside reading the source tree; all output writing goes through
5
+ // lib/write.js so determinism and the fail-closed lint gate live in one
6
+ // place instead of being duplicated per adapter.
7
+ //
8
+ // @typedef {object} ContentNode
9
+ // @property {string} path - package-relative path under content/, forward slashes
10
+ // @property {string} body - full file contents, including any frontmatter block
11
+ //
12
+ // @typedef {object} ConversionWarning
13
+ // @property {string} code
14
+ // @property {string} message
15
+ // @property {string} [file] - source-relative path, for user-facing messages
16
+ //
17
+ // @typedef {object} PackageDraft
18
+ // @property {object} manifest
19
+ // @property {ContentNode[]} contentNodes
20
+ // @property {{ path: string, body: string|Buffer }[]} [files] - other package files:
21
+ // under sources/ or media/, or structure.ttl
22
+ // @property {ConversionWarning[]} warnings
23
+ import { UsageError } from '../target.js';
24
+ import * as directory from './directory.js';
25
+ import * as markdown from './markdown.js';
26
+ import * as obsidian from './obsidian.js';
27
+ import * as openapi from './openapi.js';
28
+ import * as pdf from './pdf.js';
29
+ import * as youtube from './youtube.js';
30
+
31
+ export const ADAPTER_NAMES = ['directory', 'markdown', 'obsidian', 'openapi', 'pdf', 'youtube'];
32
+
33
+ const IMPLEMENTED = {
34
+ directory,
35
+ markdown,
36
+ obsidian,
37
+ openapi,
38
+ pdf,
39
+ youtube,
40
+ };
41
+
42
+ /**
43
+ * @param {string} name
44
+ * @returns {{ name: string, detect: (inputPath: string) => boolean, convert: Function }}
45
+ */
46
+ export function getAdapter(name) {
47
+ const adapter = IMPLEMENTED[name];
48
+ if (!adapter) {
49
+ if (ADAPTER_NAMES.includes(name)) {
50
+ throw new UsageError(`The "${name}" adapter is not implemented yet.`);
51
+ }
52
+ throw new UsageError(`Unknown adapter "${name}"; expected one of: ${ADAPTER_NAMES.join(', ')}.`);
53
+ }
54
+ return adapter;
55
+ }
56
+
57
+ /** Adapters usable by lib/detect.js auto-detection, in priority order. */
58
+ export function implementedAdapters() {
59
+ return Object.values(IMPLEMENTED);
60
+ }
@@ -0,0 +1,65 @@
1
+ // `markdown` adapter: a single Markdown file, or a glob of files with no
2
+ // directory structure worth preserving. Each becomes content/<slug>.md,
3
+ // where the slug is derived from the file's title, not its source path.
4
+ import { existsSync, globSync, statSync } from 'node:fs';
5
+ import { basename, extname } from 'node:path';
6
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
7
+ import { buildManifest } from '../manifest.js';
8
+ import { slugify } from '../slug.js';
9
+ import { UsageError, isGlobPattern } from '../target.js';
10
+
11
+ export const name = 'markdown';
12
+ export const DEFAULT_TYPE = 'Document';
13
+
14
+
15
+ /**
16
+ * @param {string} inputPath
17
+ * @returns {boolean} true for a single .md/.markdown file (a directory or
18
+ * glob input is handled by the `directory` adapter or requires an
19
+ * explicit --from, respectively -- see lib/detect.js).
20
+ */
21
+ export function detect(inputPath) {
22
+ if (isGlobPattern(inputPath)) return false;
23
+ if (!existsSync(inputPath) || !statSync(inputPath).isFile()) return false;
24
+ return /\.(md|markdown)$/i.test(inputPath);
25
+ }
26
+
27
+ /**
28
+ * @param {object} ctx
29
+ * @param {string} ctx.inputPath
30
+ * @param {{ id?: string, title?: string, version?: string }} ctx.options
31
+ * @returns {import('./index.js').PackageDraft}
32
+ */
33
+ export function convert({ inputPath, options }) {
34
+ const manifest = buildManifest(options);
35
+ const files = resolveFiles(inputPath);
36
+ if (files.length === 0) {
37
+ throw new UsageError(`No Markdown files matched "${inputPath}".`);
38
+ }
39
+
40
+ const usedSlugs = new Map(); // slug -> count seen so far, for deterministic -2/-3 suffixes
41
+ const type = options.type ?? DEFAULT_TYPE;
42
+ const contentNodes = files.map((absPath) => buildContentNode(absPath, usedSlugs, type));
43
+
44
+ return { manifest, contentNodes, warnings: [] };
45
+ }
46
+
47
+ function resolveFiles(inputPath) {
48
+ const paths = isGlobPattern(inputPath) ? [...globSync(inputPath)] : [inputPath];
49
+ return paths
50
+ .filter((p) => statSync(p).isFile())
51
+ .sort();
52
+ }
53
+
54
+ function buildContentNode(absPath, usedSlugs, type) {
55
+ const { data, content, raw } = readContentFile(absPath);
56
+ const title = deriveTitle(data, content, basename(absPath, extname(absPath)));
57
+ const slug = uniqueSlug(slugify(title), usedSlugs);
58
+ return { path: `content/${slug}.md`, body: ensureOkf(raw, data, { type, title }) };
59
+ }
60
+
61
+ function uniqueSlug(baseSlug, usedSlugs) {
62
+ const count = usedSlugs.get(baseSlug) ?? 0;
63
+ usedSlugs.set(baseSlug, count + 1);
64
+ return count === 0 ? baseSlug : `${baseSlug}-${count + 1}`;
65
+ }
@@ -0,0 +1,199 @@
1
+ // `obsidian` adapter: an Obsidian vault directory becomes one content node
2
+ // per note, preserving the vault's folder structure under content/ and
3
+ // rewriting [[wikilink]] syntax to relative Markdown links.
4
+ import { existsSync, statSync } from 'node:fs';
5
+ import { basename, join, posix } from 'node:path';
6
+ import { walkFiles } from '../walk.js';
7
+ import { readContentFile, ensureOkf, deriveTitle } from '../frontmatter.js';
8
+ import { buildManifest } from '../manifest.js';
9
+ import { matchesAny } from '../glob.js';
10
+ import { slugify } from '../slug.js';
11
+ import { UsageError } from '../target.js';
12
+
13
+ export const name = 'obsidian';
14
+ export const DEFAULT_TYPE = 'Note';
15
+
16
+ const WIKILINK = /(!?)\[\[([^\]|#]+)(#[^\]|]+)?(?:\|([^\]]+))?\]\]/g;
17
+
18
+ /**
19
+ * @param {string} inputPath
20
+ * @returns {boolean} true if `inputPath` is a directory containing a
21
+ * top-level `.obsidian/` folder -- Obsidian's own vault marker.
22
+ */
23
+ export function detect(inputPath) {
24
+ if (!existsSync(inputPath) || !statSync(inputPath).isDirectory()) return false;
25
+ const obsidianDir = join(inputPath, '.obsidian');
26
+ return existsSync(obsidianDir) && statSync(obsidianDir).isDirectory();
27
+ }
28
+
29
+ /**
30
+ * @param {object} ctx
31
+ * @param {string} ctx.inputPath
32
+ * @param {{ id?: string, title?: string, version?: string, exclude?: string[] }} ctx.options
33
+ * @returns {import('./index.js').PackageDraft}
34
+ */
35
+ export function convert({ inputPath, options }) {
36
+ const manifest = buildManifest({ ...options, title: options.title ?? basename(inputPath) });
37
+ const type = options.type ?? DEFAULT_TYPE;
38
+ const excludePatterns = options.exclude ?? [];
39
+ const allNotePaths = walkFiles(inputPath)
40
+ .filter((f) => f.endsWith('.md'))
41
+ .filter((f) => f !== '.obsidian' && !f.startsWith('.obsidian/'));
42
+
43
+ if (allNotePaths.length === 0) {
44
+ throw new UsageError(`No notes found under ${inputPath}.`);
45
+ }
46
+
47
+ const allNotes = allNotePaths.map((relPath) => ({
48
+ relPath,
49
+ excluded: matchesAny(relPath, excludePatterns),
50
+ ...readContentFile(join(inputPath, relPath)),
51
+ }));
52
+
53
+ const noteIndex = buildNoteIndex(allNotes);
54
+ const warnings = [];
55
+ const contentNodes = allNotes
56
+ .filter((note) => !note.excluded)
57
+ .map((note) => buildContentNode(note, noteIndex, warnings, type));
58
+
59
+ return { manifest, contentNodes, warnings };
60
+ }
61
+
62
+ function buildContentNode(note, noteIndex, warnings, type) {
63
+ const title = deriveTitle(note.data, note.content, basename(note.relPath, '.md'));
64
+ const body = rewriteWikilinks(ensureOkf(note.raw, note.data, { type, title }), note, noteIndex, warnings);
65
+ return { path: `content/${note.relPath}`, body };
66
+ }
67
+
68
+ /**
69
+ * Rewrites [[wikilink]] syntax line-by-line, skipping lines inside fenced
70
+ * (```) code blocks so link syntax that happens to appear in a code sample
71
+ * is never touched.
72
+ */
73
+ function rewriteWikilinks(text, sourceNote, noteIndex, warnings) {
74
+ let inFence = false;
75
+ return text
76
+ .split('\n')
77
+ .map((line) => {
78
+ if (/^\s*```/.test(line)) {
79
+ inFence = !inFence;
80
+ return line;
81
+ }
82
+ if (inFence) return line;
83
+ return line.replace(WIKILINK, (match, bang, rawTarget, heading, alias) =>
84
+ rewriteMatch({ match, bang, rawTarget, heading, alias, sourceNote, noteIndex, warnings })
85
+ );
86
+ })
87
+ .join('\n');
88
+ }
89
+
90
+ function rewriteMatch({ match, bang, rawTarget, heading, alias, sourceNote, noteIndex, warnings }) {
91
+ const target = rawTarget.trim();
92
+
93
+ if (bang === '!') {
94
+ warnings.push({
95
+ code: 'W_UNSUPPORTED_EMBED',
96
+ file: sourceNote.relPath,
97
+ message: `Embed "${match}" has no CommonMark equivalent; left as literal text.`,
98
+ });
99
+ return match;
100
+ }
101
+
102
+ const resolved = resolveNote(target, noteIndex);
103
+
104
+ if (!resolved) {
105
+ warnings.push({
106
+ code: 'W_UNRESOLVED_WIKILINK',
107
+ file: sourceNote.relPath,
108
+ message: `Wikilink to "${target}" does not match any note in the vault; left as literal text.`,
109
+ });
110
+ return match;
111
+ }
112
+
113
+ if (resolved.excluded) {
114
+ warnings.push({
115
+ code: 'W_EXCLUDED_WIKILINK',
116
+ file: sourceNote.relPath,
117
+ message: `Wikilink to "${target}" points to an excluded note ("${resolved.relPath}"); left as literal text.`,
118
+ });
119
+ return match;
120
+ }
121
+
122
+ const displayText = alias ?? target;
123
+ const relPath = relativeContentLink(sourceNote.relPath, resolved.relPath);
124
+ const anchor = heading ? `#${slugify(heading.slice(1))}` : '';
125
+ return `[${displayText}](${formatLinkDestination(relPath + anchor)})`;
126
+ }
127
+
128
+ /**
129
+ * A CommonMark link destination containing an unescaped space is not
130
+ * parsed as a link at all -- and vault filenames commonly contain spaces
131
+ * (e.g. "Setup Guide.md") -- so wrap the destination in angle brackets
132
+ * whenever it needs them, per the CommonMark link-destination grammar.
133
+ * @param {string} destination
134
+ */
135
+ function formatLinkDestination(destination) {
136
+ if (!/[\s<>]/.test(destination)) return destination;
137
+ return `<${destination.replace(/[<>]/g, '\\$&')}>`;
138
+ }
139
+
140
+ /**
141
+ * @param {string} fromRelPath - the linking note's path, relative to content/
142
+ * @param {string} toRelPath - the target note's path, relative to content/
143
+ * @returns {string} a POSIX relative path from one to the other
144
+ */
145
+ function relativeContentLink(fromRelPath, toRelPath) {
146
+ const fromDir = posix.dirname(fromRelPath);
147
+ const rel = posix.relative(fromDir === '.' ? '' : fromDir, toRelPath);
148
+ return rel.startsWith('.') ? rel : `./${rel}`;
149
+ }
150
+
151
+ function buildNoteIndex(notes) {
152
+ const byPath = new Map(); // path without extension, lowercased -> note
153
+ const byBasename = new Map(); // basename without extension, lowercased -> note[] (sorted by relPath)
154
+ const byAlias = new Map(); // alias, lowercased -> note
155
+
156
+ for (const note of notes) {
157
+ const withoutExt = note.relPath.replace(/\.md$/i, '');
158
+ byPath.set(withoutExt.toLowerCase(), note);
159
+
160
+ const baseKey = basename(withoutExt).toLowerCase();
161
+ if (!byBasename.has(baseKey)) byBasename.set(baseKey, []);
162
+ byBasename.get(baseKey).push(note);
163
+
164
+ for (const alias of normalizeAliases(note.data.aliases)) {
165
+ const aliasKey = alias.toLowerCase();
166
+ if (!byAlias.has(aliasKey)) byAlias.set(aliasKey, note);
167
+ }
168
+ }
169
+
170
+ for (const list of byBasename.values()) {
171
+ list.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
172
+ }
173
+
174
+ return { byPath, byBasename, byAlias };
175
+ }
176
+
177
+ function normalizeAliases(aliases) {
178
+ if (Array.isArray(aliases)) return aliases.filter((a) => typeof a === 'string');
179
+ if (typeof aliases === 'string') return [aliases];
180
+ return [];
181
+ }
182
+
183
+ /**
184
+ * Resolves a raw wikilink target to a note, preferring an exact
185
+ * (possibly path-qualified) match, then an alias, then a basename match --
186
+ * the same fallback order Obsidian itself uses. When multiple notes share a
187
+ * basename, the lexicographically-first match is chosen deterministically.
188
+ */
189
+ function resolveNote(target, noteIndex) {
190
+ const normalized = target.replace(/\.md$/i, '');
191
+ const key = normalized.toLowerCase();
192
+
193
+ if (noteIndex.byPath.has(key)) return noteIndex.byPath.get(key);
194
+ if (noteIndex.byAlias.has(key)) return noteIndex.byAlias.get(key);
195
+
196
+ const baseKey = basename(normalized).toLowerCase();
197
+ const candidates = noteIndex.byBasename.get(baseKey);
198
+ return candidates ? candidates[0] : null;
199
+ }
@@ -0,0 +1,114 @@
1
+ // Parses an OpenAPI 3.x document (JSON or YAML) and walks its operations.
2
+ // Deliberately does not use a full OpenAPI parser/validator: content nodes
3
+ // only need to *display* request/response shapes as fenced code blocks, not
4
+ // machine-validate them, so only a small local (#/...) $ref resolver is
5
+ // implemented -- an external or unresolvable $ref is left as literal
6
+ // {"$ref": "..."} text in the rendered output rather than failing.
7
+ import { readFileSync } from 'node:fs';
8
+ import * as yaml from 'js-yaml';
9
+ import { UsageError } from '../../target.js';
10
+
11
+ export const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
12
+
13
+ /**
14
+ * @param {string} inputPath
15
+ * @returns {object} the parsed OpenAPI 3.x document
16
+ */
17
+ export function parseOpenApiDocument(inputPath) {
18
+ const raw = readFileSync(inputPath, 'utf8');
19
+ const isYaml = /\.ya?ml$/i.test(inputPath);
20
+
21
+ let doc;
22
+ try {
23
+ doc = isYaml ? yaml.load(raw) : JSON.parse(raw);
24
+ } catch (err) {
25
+ throw new UsageError(`Failed to parse "${inputPath}" as ${isYaml ? 'YAML' : 'JSON'}: ${err.message}`);
26
+ }
27
+
28
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
29
+ throw new UsageError(`"${inputPath}" does not contain an OpenAPI document object.`);
30
+ }
31
+ if (typeof doc.swagger === 'string') {
32
+ throw new UsageError(`"${inputPath}" is an OpenAPI 2.0 (Swagger) document; only OpenAPI 3.x is supported.`);
33
+ }
34
+ if (typeof doc.openapi !== 'string' || !/^3\.\d+\.\d+/.test(doc.openapi)) {
35
+ throw new UsageError(`"${inputPath}" does not declare a supported "openapi: 3.x.x" version.`);
36
+ }
37
+
38
+ return doc;
39
+ }
40
+
41
+ /**
42
+ * @param {object} doc
43
+ * @returns {Array<{ path: string, method: string, operation: object }>}
44
+ * sorted by path (lexicographic), then by a fixed HTTP method order --
45
+ * not object-insertion order, which isn't guaranteed stable across
46
+ * different JSON/YAML parsers.
47
+ */
48
+ export function collectOperations(doc) {
49
+ const paths = doc.paths ?? {};
50
+ const operations = [];
51
+
52
+ for (const path of Object.keys(paths)) {
53
+ const pathItem = paths[path] ?? {};
54
+ for (const method of HTTP_METHODS) {
55
+ if (pathItem[method]) {
56
+ operations.push({ path, method, operation: pathItem[method] });
57
+ }
58
+ }
59
+ }
60
+
61
+ operations.sort((a, b) => {
62
+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;
63
+ return HTTP_METHODS.indexOf(a.method) - HTTP_METHODS.indexOf(b.method);
64
+ });
65
+
66
+ return operations;
67
+ }
68
+
69
+ /**
70
+ * Resolves a local (same-document) JSON Pointer $ref, e.g.
71
+ * "#/components/schemas/Widget". Returns undefined if the ref doesn't
72
+ * resolve within `doc`.
73
+ * @param {object} doc
74
+ * @param {string} ref
75
+ */
76
+ export function resolveLocalRef(doc, ref) {
77
+ if (typeof ref !== 'string' || !ref.startsWith('#/')) return undefined;
78
+ return ref
79
+ .slice(2)
80
+ .split('/')
81
+ .map(decodeRefSegment)
82
+ .reduce((node, key) => (node == null ? undefined : node[key]), doc);
83
+ }
84
+
85
+ function decodeRefSegment(segment) {
86
+ return segment.replace(/~1/g, '/').replace(/~0/g, '~');
87
+ }
88
+
89
+ /**
90
+ * Recursively expands local $ref pointers within a schema/value so rendered
91
+ * code blocks show the actual shape rather than a bare pointer. An external
92
+ * ref (doesn't start with "#/"), an unresolvable ref, or a ref cycle is left
93
+ * as a literal `{ "$ref": "..." }` marker instead of failing.
94
+ * @param {*} value
95
+ * @param {object} doc
96
+ * @param {Set<string>} [seen]
97
+ */
98
+ export function resolveSchema(value, doc, seen = new Set()) {
99
+ if (value === null || typeof value !== 'object') return value;
100
+ if (Array.isArray(value)) return value.map((item) => resolveSchema(item, doc, seen));
101
+
102
+ if (typeof value.$ref === 'string') {
103
+ if (!value.$ref.startsWith('#/') || seen.has(value.$ref)) return { $ref: value.$ref };
104
+ const target = resolveLocalRef(doc, value.$ref);
105
+ if (target === undefined) return { $ref: value.$ref };
106
+ return resolveSchema(target, doc, new Set(seen).add(value.$ref));
107
+ }
108
+
109
+ const result = {};
110
+ for (const [key, nested] of Object.entries(value)) {
111
+ result[key] = resolveSchema(nested, doc, seen);
112
+ }
113
+ return result;
114
+ }