@lexibase/rdx-core 1.4.0 → 2.1.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,25 @@
1
+ import { RdxContentSource, RdxDocPage, RdxProject } from '@lexibase/rdx-types';
2
+
3
+ type DocumentationDiagnostic = {
4
+ file: string;
5
+ line: number;
6
+ column: number;
7
+ code: 'page' | 'anchor' | 'asset' | 'syntax';
8
+ message: string;
9
+ };
10
+ type DocumentationCheck = {
11
+ checkedPages: number;
12
+ diagnostics: DocumentationDiagnostic[];
13
+ };
14
+ /** Host adapters can describe aliases without changing the project's authoring API. */
15
+ type DocumentationCheckOptions = {
16
+ documentRoutes?: (source: RdxContentSource, page: RdxDocPage, pages: readonly RdxDocPage[]) => string[];
17
+ sourceRoute?: (source: RdxContentSource) => string;
18
+ redirects?: Readonly<Record<string, string>>;
19
+ };
20
+ /** Read static MDX only. Never build Next, evaluate document JS or request URLs. */
21
+ declare function checkDocumentation(project: RdxProject, options?: DocumentationCheckOptions): DocumentationCheck;
22
+ declare function formatDocumentationCheck(report: DocumentationCheck): string;
23
+
24
+ export { checkDocumentation, formatDocumentationCheck };
25
+ export type { DocumentationCheck, DocumentationCheckOptions, DocumentationDiagnostic };
@@ -0,0 +1,310 @@
1
+ import {
2
+ getDocsIndex,
3
+ getSourceOptions,
4
+ parseStaticDocument
5
+ } from "../chunk-CGOXC3S6.js";
6
+ import {
7
+ getContentSources,
8
+ isFallbackPage
9
+ } from "../chunk-SNNEXRLQ.js";
10
+ import {
11
+ RdxDocumentLinkError,
12
+ createDocumentLinkResolver
13
+ } from "../chunk-LCBSNAUH.js";
14
+ import {
15
+ headingText
16
+ } from "../chunk-FPBRKD4M.js";
17
+ import {
18
+ remarkDocumentationComponents
19
+ } from "../chunk-J7VCQHSL.js";
20
+
21
+ // src/check/index.ts
22
+ import fs from "fs";
23
+ import path from "path";
24
+ import GithubSlugger from "github-slugger";
25
+ import remarkGfm from "remark-gfm";
26
+ import remarkMdx from "remark-mdx";
27
+ import remarkParse from "remark-parse";
28
+ import { unified } from "unified";
29
+ var parser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx).use(remarkDocumentationComponents);
30
+ var sourceRoute = (source) => [source.basePath ?? "/docs", source.routePrefix].filter(Boolean).join("/");
31
+ var documentRoute = (source, page) => `${sourceRoute(source)}/${page.slug.split("/").map(encodeURIComponent).join("/")}`;
32
+ var identifier = (value) => value.trim().replace(/\s+/g, " ").toLowerCase();
33
+ function walk(node, visit) {
34
+ visit(node);
35
+ for (const child of node.children ?? []) walk(child, visit);
36
+ }
37
+ function parse(content) {
38
+ const tree = parser.runSync(parser.parse(content), { value: content });
39
+ const anchors = /* @__PURE__ */ new Set();
40
+ const references = [];
41
+ const definitions = /* @__PURE__ */ new Map();
42
+ const slugger = new GithubSlugger();
43
+ let dynamicIds = false;
44
+ walk(tree, (node) => {
45
+ if (node.type === "definition" && node.identifier && node.url && !definitions.has(identifier(node.identifier)))
46
+ definitions.set(identifier(node.identifier), node.url);
47
+ });
48
+ walk(tree, (node) => {
49
+ if (node.type === "heading") anchors.add(slugger.slug(headingText(node)));
50
+ if (node.type === "link" || node.type === "image") {
51
+ if (typeof node.url === "string")
52
+ references.push({
53
+ href: node.url,
54
+ image: node.type === "image",
55
+ position: node.position
56
+ });
57
+ }
58
+ if ((node.type === "linkReference" || node.type === "imageReference") && node.identifier) {
59
+ const href = definitions.get(identifier(node.identifier));
60
+ if (href)
61
+ references.push({
62
+ href,
63
+ image: node.type === "imageReference",
64
+ position: node.position
65
+ });
66
+ }
67
+ if (!node.type.startsWith("mdxJsx")) return;
68
+ for (const attribute of node.attributes ?? []) {
69
+ if (attribute.name === "id" || node.name === "a" && attribute.name === "name") {
70
+ if (typeof attribute.value === "string") anchors.add(attribute.value);
71
+ else if (attribute.value) dynamicIds = true;
72
+ }
73
+ if ((node.name === "a" && attribute.name === "href" || node.name === "img" && attribute.name === "src") && typeof attribute.value === "string") {
74
+ references.push({
75
+ href: attribute.value,
76
+ image: node.name === "img",
77
+ position: node.position
78
+ });
79
+ }
80
+ }
81
+ });
82
+ return { anchors, references, dynamicIds };
83
+ }
84
+ function checkDocumentation(project, options = {}) {
85
+ const diagnostics = [];
86
+ const documents = [];
87
+ const routes = /* @__PURE__ */ new Map();
88
+ const coreRoutes = /* @__PURE__ */ new Map();
89
+ const roots = /* @__PURE__ */ new Set(["/robots.txt", "/sitemap.xml"]);
90
+ const prefixes = [];
91
+ const redirects = new Map(Object.entries(options.redirects ?? {}));
92
+ const failed = /* @__PURE__ */ new Set();
93
+ const origin = project.config.metadata.metadataBase ? new URL(project.config.metadata.metadataBase).origin : "https://rdx.invalid";
94
+ const key = (href) => decodeURIComponent(new URL(href, origin).pathname).replace(/\/$/, "") || "/";
95
+ const rootFor = options.sourceRoute ?? sourceRoute;
96
+ const relativeFile = (file) => path.relative(project.rootDir, file).split(path.sep).join("/") || ".";
97
+ function syntax(error, file, offset = 0) {
98
+ const value = error;
99
+ diagnostics.push({
100
+ file: relativeFile(file),
101
+ line: value.mark ? value.mark.line + 1 : (value.line ?? 1) + offset,
102
+ column: value.column ?? (value.mark ? value.mark.column + 1 : 1),
103
+ code: "syntax",
104
+ message: value.message ?? String(error)
105
+ });
106
+ }
107
+ const sources = getContentSources(
108
+ project.locale ? { ...project, locale: void 0 } : project
109
+ );
110
+ if (project.localization) {
111
+ const primary = project.localization.locales.find(
112
+ (locale) => locale.code === project.localization.defaultLocale
113
+ );
114
+ prefixes.push(["/docs", `/${primary.path}/docs`]);
115
+ }
116
+ for (const source of sources) {
117
+ if (source.redirectTo !== void 0) {
118
+ const destination = sources.find(
119
+ (entry) => entry.routePrefix === source.redirectTo && entry.basePath === source.basePath
120
+ );
121
+ prefixes.push([key(rootFor(source)), key(rootFor(destination))]);
122
+ continue;
123
+ }
124
+ let pages;
125
+ try {
126
+ if (source.fallbackDocsDir) {
127
+ const primaryPages = new Set(
128
+ getDocsIndex(
129
+ { docsDir: path.resolve(project.rootDir, source.fallbackDocsDir) },
130
+ (error, file) => syntax(error, file)
131
+ ).flatMap((category) => category.pages.map((page) => page.slug))
132
+ );
133
+ for (const category of getDocsIndex(
134
+ { docsDir: path.resolve(project.rootDir, source.docsDir) },
135
+ (error, file) => syntax(error, file)
136
+ ))
137
+ for (const page of category.pages)
138
+ if (!primaryPages.has(page.slug))
139
+ diagnostics.push({
140
+ file: relativeFile(page.sourcePath),
141
+ line: 1,
142
+ column: 1,
143
+ code: "page",
144
+ message: "Translation has no primary-language counterpart with the same relative MDX path."
145
+ });
146
+ }
147
+ pages = getDocsIndex(getSourceOptions(project, source), (error, file) => {
148
+ syntax(error, file);
149
+ failed.add(file);
150
+ }).flatMap((category) => category.pages);
151
+ } catch (error) {
152
+ syntax(error, getSourceOptions(project, source).docsDir);
153
+ continue;
154
+ }
155
+ roots.add(key(rootFor(source)));
156
+ if (project.config.search)
157
+ roots.add(`/rdx-search/${source.routePrefix || "_"}`);
158
+ for (const page of pages) {
159
+ const hrefs = options.documentRoutes?.(source, page, pages) ?? [
160
+ documentRoute(source, page)
161
+ ];
162
+ const document = {
163
+ page,
164
+ source,
165
+ href: hrefs[0],
166
+ lineOffset: 0
167
+ };
168
+ documents.push(document);
169
+ for (const href of hrefs) routes.set(key(href), document);
170
+ coreRoutes.set(key(documentRoute(source, page)), document);
171
+ if (page === pages[0]) {
172
+ routes.set(key(rootFor(source)), document);
173
+ if (source === project.sources[0]) routes.set("/docs", document);
174
+ }
175
+ }
176
+ }
177
+ if (project.config.homepage?.enabled) roots.add("/");
178
+ else redirects.set("/", "/docs");
179
+ for (const document of documents) {
180
+ if (failed.has(document.page.sourcePath)) continue;
181
+ try {
182
+ const raw = fs.readFileSync(document.page.sourcePath, "utf8");
183
+ const content = parseStaticDocument(raw).content;
184
+ document.lineOffset = (raw.slice(0, raw.length - content.length).match(/\n/g) ?? []).length;
185
+ document.parsed = parse(content);
186
+ } catch (error) {
187
+ syntax(error, document.page.sourcePath, document.lineOffset);
188
+ }
189
+ }
190
+ function redirectRoute(pathname) {
191
+ const seen = /* @__PURE__ */ new Set();
192
+ while (!seen.has(pathname)) {
193
+ seen.add(pathname);
194
+ const exact = redirects.get(pathname);
195
+ const prefix = prefixes.find(
196
+ ([from]) => pathname === from || pathname.startsWith(`${from}/`)
197
+ );
198
+ const next = exact ? key(exact) : prefix ? prefix[1] + pathname.slice(prefix[0].length) : pathname;
199
+ if (next === pathname) return pathname;
200
+ pathname = next;
201
+ }
202
+ throw new Error("The destination contains a redirect loop.");
203
+ }
204
+ for (const document of documents) {
205
+ const parsed = document.parsed;
206
+ if (!parsed) continue;
207
+ const contentSource = isFallbackPage(
208
+ project,
209
+ document.source,
210
+ document.page.sourcePath
211
+ ) ? sources.find(
212
+ (source) => source.id === document.source.id && source.docsDir === document.source.fallbackDocsDir && !source.fallbackDocsDir
213
+ ) : document.source;
214
+ const resolve = createDocumentLinkResolver({
215
+ sourceRoot: getSourceOptions(project, contentSource).docsDir,
216
+ sourcePath: document.page.sourcePath,
217
+ routePrefix: contentSource.routePrefix,
218
+ basePath: contentSource.basePath,
219
+ virtualPaths: !!contentSource.fallbackDocsDir,
220
+ documents: documents.filter((entry) => entry.source === contentSource).map((entry) => entry.page)
221
+ });
222
+ for (const reference of parsed.references) {
223
+ let code = reference.image ? "asset" : "page";
224
+ try {
225
+ const url = new URL(
226
+ reference.href,
227
+ `${origin}${contentSource === document.source ? document.href : documentRoute(contentSource, document.page)}`
228
+ );
229
+ if (!["http:", "https:"].includes(url.protocol)) continue;
230
+ if (url.origin !== origin) continue;
231
+ if (!project.config.metadata.metadataBase && /^(?:[a-z][\w+.-]*:|\/\/)/i.test(reference.href))
232
+ continue;
233
+ let target;
234
+ let pathname;
235
+ const explicitMdx = !reference.image && !/^(?:[a-z][\w+.-]*:|\/|#|\?)/i.test(reference.href) && /\.mdx(?:[?#]|$)/.test(decodeURIComponent(reference.href));
236
+ if (explicitMdx) {
237
+ const resolved = resolve(reference.href);
238
+ pathname = key(resolved);
239
+ target = coreRoutes.get(pathname);
240
+ } else {
241
+ pathname = redirectRoute(key(url.href));
242
+ if (!reference.image) target = routes.get(pathname);
243
+ }
244
+ if (target) {
245
+ if (url.hash) {
246
+ code = "anchor";
247
+ const anchor = decodeURIComponent(url.hash.slice(1));
248
+ if (target.parsed && !target.parsed.dynamicIds && !target.parsed.anchors.has(anchor))
249
+ throw new Error(
250
+ `Section "#${anchor}" does not exist in ${relativeFile(target.page.sourcePath)}.`
251
+ );
252
+ }
253
+ continue;
254
+ }
255
+ if (!reference.image && roots.has(pathname)) continue;
256
+ code = reference.image || !/^\/(?:[^/]+\/)?docs(?:\/|$)/.test(pathname) ? "asset" : "page";
257
+ if (pathname.includes("\\") || pathname.includes("\0"))
258
+ throw new Error("Use a valid URL with forward slashes.");
259
+ const publicRoot = path.resolve(project.rootDir, "public");
260
+ const asset = path.resolve(publicRoot, `.${pathname}`);
261
+ const relative = path.relative(publicRoot, asset);
262
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
263
+ throw new Error("The destination escapes public/.");
264
+ let exists = false;
265
+ try {
266
+ exists = fs.statSync(asset).isFile();
267
+ } catch {
268
+ }
269
+ if (!exists)
270
+ throw new Error(
271
+ code === "page" ? `Documentation page "${pathname}" does not exist.` : `Local file "${pathname}" does not exist in public/.`
272
+ );
273
+ } catch (error) {
274
+ const value = error instanceof RdxDocumentLinkError ? error.reason : error instanceof Error ? error.message : String(error);
275
+ diagnostics.push({
276
+ file: relativeFile(document.page.sourcePath),
277
+ line: (reference.position?.start.line ?? 1) + document.lineOffset,
278
+ column: reference.position?.start.column ?? 1,
279
+ code,
280
+ message: `"${reference.href}": ${value}`
281
+ });
282
+ }
283
+ }
284
+ }
285
+ diagnostics.sort(
286
+ (a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column
287
+ );
288
+ const unique = [
289
+ ...new Map(
290
+ diagnostics.map((diagnostic) => [JSON.stringify(diagnostic), diagnostic])
291
+ ).values()
292
+ ];
293
+ return {
294
+ checkedPages: new Set(documents.map((document) => document.page.sourcePath)).size,
295
+ diagnostics: unique
296
+ };
297
+ }
298
+ function formatDocumentationCheck(report) {
299
+ const lines = report.diagnostics.map(
300
+ (entry) => `${entry.file}:${entry.line}:${entry.column} [${entry.code}] ${entry.message}`
301
+ );
302
+ lines.push(
303
+ `RDX check ${report.diagnostics.length ? "failed" : "passed"}: ${report.checkedPages} ${report.checkedPages === 1 ? "page" : "pages"} checked, ${report.diagnostics.length} ${report.diagnostics.length === 1 ? "problem" : "problems"}.`
304
+ );
305
+ return lines.join("\n");
306
+ }
307
+ export {
308
+ checkDocumentation,
309
+ formatDocumentationCheck
310
+ };
@@ -0,0 +1,233 @@
1
+ // src/content/static-source.ts
2
+ import matter from "gray-matter";
3
+ function parseStaticDocument(source) {
4
+ const text = source.replace(/^\uFEFF/, "");
5
+ if (text.startsWith("---") && text[3] !== "-") {
6
+ const language = matter.language(text).name.toLowerCase();
7
+ if (language && !["yaml", "yml", "json"].includes(language))
8
+ throw new Error(
9
+ "rdx check accepts YAML or JSON frontmatter, without executing document code."
10
+ );
11
+ }
12
+ return matter(source, {});
13
+ }
14
+
15
+ // src/content/index.ts
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import matter2 from "gray-matter";
19
+ var MDX_EXTENSION = ".mdx";
20
+ var DEFAULT_POSITION = Number.MAX_SAFE_INTEGER;
21
+ function getDocsRoot(docsDir = "docs") {
22
+ return path.resolve(
23
+ /* turbopackIgnore: true */
24
+ process.cwd(),
25
+ docsDir
26
+ );
27
+ }
28
+ function toTitle(value) {
29
+ return value.replace(/[-_]/g, " ").replace(/\b\w/g, (character) => character.toUpperCase());
30
+ }
31
+ function isRecord(value) {
32
+ return typeof value === "object" && value !== null;
33
+ }
34
+ function stringValue(value, fallback) {
35
+ return typeof value === "string" && value.trim() ? value : fallback;
36
+ }
37
+ function numberValue(value, fallback = DEFAULT_POSITION) {
38
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
39
+ }
40
+ function readCategoryMeta(categoryPath, fallbackTitle) {
41
+ const metaPath = path.join(categoryPath, "_category.json");
42
+ if (!fs.existsSync(metaPath)) {
43
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
44
+ }
45
+ try {
46
+ const parsed = JSON.parse(fs.readFileSync(metaPath, "utf8"));
47
+ if (!isRecord(parsed)) {
48
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
49
+ }
50
+ return {
51
+ title: stringValue(parsed.title, fallbackTitle),
52
+ position: numberValue(parsed.sidebar_position)
53
+ };
54
+ } catch {
55
+ return { title: fallbackTitle, position: DEFAULT_POSITION };
56
+ }
57
+ }
58
+ function findMdxFiles(directory) {
59
+ const entries = fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
60
+ return entries.flatMap((entry) => {
61
+ const entryPath = path.join(directory, entry.name);
62
+ if (entry.isDirectory()) return findMdxFiles(entryPath);
63
+ if (entry.isFile() && entry.name.endsWith(MDX_EXTENSION)) return [entryPath];
64
+ return [];
65
+ });
66
+ }
67
+ function slugFromRelativePath(relativePath) {
68
+ return relativePath.split(path.sep).join("/").replace(/\.mdx$/, "");
69
+ }
70
+ function isSafeSlug(slug) {
71
+ if (path.isAbsolute(slug) || slug.includes("\\")) return false;
72
+ return slug.split("/").every((segment) => segment && segment !== "." && segment !== "..");
73
+ }
74
+ function getDocsIndex({ docsDir, fallbackDocsDir, fallbackOnly } = {}, onError) {
75
+ if (fallbackOnly)
76
+ return getDocsIndex({ docsDir: fallbackDocsDir ?? docsDir }, onError);
77
+ if (fallbackDocsDir) {
78
+ const primary = getDocsIndex({ docsDir: fallbackDocsDir }, onError);
79
+ const translated = getDocsIndex({ docsDir }, onError);
80
+ const pages = new Map(
81
+ translated.flatMap(
82
+ (category) => category.pages.map((page) => [page.slug, page])
83
+ )
84
+ );
85
+ return primary.map((category) => ({
86
+ ...category,
87
+ title: readCategoryMeta(
88
+ path.join(
89
+ getDocsRoot(docsDir),
90
+ category.id === "_root" ? "" : category.id
91
+ ),
92
+ category.title
93
+ ).title,
94
+ pages: category.pages.map((page) => ({
95
+ ...pages.get(page.slug) ?? page,
96
+ position: page.position
97
+ }))
98
+ }));
99
+ }
100
+ const docsRoot = getDocsRoot(docsDir);
101
+ if (!fs.existsSync(docsRoot)) return [];
102
+ const categories = /* @__PURE__ */ new Map();
103
+ for (const filePath of findMdxFiles(docsRoot)) {
104
+ const relativePath = path.relative(docsRoot, filePath);
105
+ const pathParts = relativePath.split(path.sep);
106
+ const categoryId = pathParts.length > 1 ? pathParts[0] ?? "_root" : "_root";
107
+ const categoryPath = categoryId === "_root" ? docsRoot : path.join(docsRoot, categoryId);
108
+ const fallbackCategoryTitle = categoryId === "_root" ? "Overview" : toTitle(categoryId);
109
+ let category = categories.get(categoryId);
110
+ if (!category) {
111
+ const meta = readCategoryMeta(categoryPath, fallbackCategoryTitle);
112
+ const createdCategory = {
113
+ id: categoryId,
114
+ title: meta.title,
115
+ position: meta.position,
116
+ pages: [],
117
+ categoryPath
118
+ };
119
+ categories.set(categoryId, createdCategory);
120
+ category = createdCategory;
121
+ }
122
+ let frontmatter = {};
123
+ try {
124
+ const raw = fs.readFileSync(filePath, "utf8");
125
+ const parsed = onError ? parseStaticDocument(raw) : matter2(raw);
126
+ frontmatter = isRecord(parsed.data) ? parsed.data : {};
127
+ } catch (error) {
128
+ if (!onError) throw error;
129
+ onError(error, filePath);
130
+ }
131
+ const slug = slugFromRelativePath(relativePath);
132
+ const fallbackTitle = toTitle(path.basename(slug));
133
+ category.pages.push({
134
+ slug,
135
+ title: stringValue(frontmatter.title, fallbackTitle),
136
+ description: stringValue(frontmatter.description, ""),
137
+ position: numberValue(frontmatter.link_position),
138
+ sourcePath: filePath
139
+ });
140
+ }
141
+ return [...categories.values()].map(({ categoryPath: _categoryPath, ...category }) => ({
142
+ ...category,
143
+ pages: category.pages.sort(
144
+ (first, second) => first.position - second.position || first.slug.localeCompare(second.slug)
145
+ )
146
+ })).sort(
147
+ (first, second) => first.position - second.position || first.title.localeCompare(second.title)
148
+ );
149
+ }
150
+ function getDocsPaths(options) {
151
+ return getDocsIndex(options).flatMap(
152
+ (category) => category.pages.map((page) => page.slug)
153
+ );
154
+ }
155
+ function getDocument(slug, { docsDir, fallbackDocsDir, fallbackOnly } = {}) {
156
+ if (!isSafeSlug(slug)) return null;
157
+ if (fallbackOnly)
158
+ return getDocument(slug, { docsDir: fallbackDocsDir ?? docsDir });
159
+ const docsRoot = getDocsRoot(docsDir);
160
+ const sourcePath = path.resolve(docsRoot, `${slug}${MDX_EXTENSION}`);
161
+ const relativePath = path.relative(docsRoot, sourcePath);
162
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath))
163
+ return null;
164
+ if (fallbackDocsDir && !getDocument(slug, { docsDir: fallbackDocsDir }))
165
+ return null;
166
+ if (!fs.existsSync(sourcePath))
167
+ return fallbackDocsDir ? getDocument(slug, { docsDir: fallbackDocsDir }) : null;
168
+ const parsed = matter2(fs.readFileSync(sourcePath, "utf8"));
169
+ return {
170
+ slug,
171
+ sourcePath,
172
+ content: parsed.content,
173
+ frontmatter: isRecord(parsed.data) ? parsed.data : {}
174
+ };
175
+ }
176
+
177
+ // src/project/index.ts
178
+ import path2 from "path";
179
+ function getSourceOptions(project, source) {
180
+ return {
181
+ docsDir: path2.resolve(project.rootDir, source.docsDir),
182
+ ...source.fallbackOnly ? { fallbackOnly: true } : {},
183
+ ...source.fallbackDocsDir ? {
184
+ fallbackDocsDir: path2.resolve(
185
+ project.rootDir,
186
+ source.fallbackDocsDir
187
+ )
188
+ } : {}
189
+ };
190
+ }
191
+ function resolveDocsRoute(project, segments = []) {
192
+ const source = project.sources.find(
193
+ (entry) => entry.routePrefix && entry.routePrefix === segments[0]
194
+ ) ?? project.sources[0];
195
+ const options = getSourceOptions(project, source);
196
+ const slug = (source.routePrefix ? segments.slice(1) : segments).join("/") || getDocsPaths(options)[0];
197
+ return {
198
+ source,
199
+ slug,
200
+ document: slug ? getDocument(slug, options) : null,
201
+ categories: getDocsIndex(options)
202
+ };
203
+ }
204
+ function getProjectDocsPaths(project) {
205
+ const paths = /* @__PURE__ */ new Set();
206
+ for (const source of project.sources) {
207
+ if (source.redirectTo !== void 0) continue;
208
+ for (const slug of getDocsPaths(getSourceOptions(project, source))) {
209
+ const route = [source.routePrefix, slug].filter(Boolean).join("/");
210
+ if (paths.has(route))
211
+ throw new Error(`Conflicting documentation route: /docs/${route}`);
212
+ if (!source.routePrefix && project.sources.some(
213
+ (other) => other.routePrefix === slug.split("/")[0]
214
+ )) {
215
+ throw new Error(
216
+ `Live documentation route /docs/${slug} conflicts with a plugin content source.`
217
+ );
218
+ }
219
+ paths.add(route);
220
+ }
221
+ }
222
+ return [...paths];
223
+ }
224
+
225
+ export {
226
+ parseStaticDocument,
227
+ getDocsIndex,
228
+ getDocsPaths,
229
+ getDocument,
230
+ getSourceOptions,
231
+ resolveDocsRoute,
232
+ getProjectDocsPaths
233
+ };
@@ -0,0 +1,14 @@
1
+ // src/mdx/heading-text.ts
2
+ function headingText(node) {
3
+ if (["image", "imageReference", "break"].includes(node.type)) return "";
4
+ if (node.children) return node.children.map(headingText).join("");
5
+ if (["mdxjsEsm", "mdxFlowExpression", "mdxTextExpression", "html"].includes(
6
+ node.type
7
+ ))
8
+ return "";
9
+ return node.value ?? "";
10
+ }
11
+
12
+ export {
13
+ headingText
14
+ };
@@ -3,14 +3,19 @@ import path from "path";
3
3
  var RdxDocumentLinkError = class extends Error {
4
4
  constructor(sourcePath, href, reason) {
5
5
  super(`[RDX] Invalid document link "${href}" in ${sourcePath}: ${reason}`);
6
+ this.reason = reason;
6
7
  this.name = "RdxDocumentLinkError";
7
8
  }
9
+ reason;
8
10
  };
9
11
  function createDocumentLinkResolver(options) {
10
12
  const root = path.resolve(options.sourceRoot);
11
13
  const current = path.resolve(options.sourcePath);
12
14
  const documents = new Map(
13
- options.documents.map((page) => [path.resolve(page.sourcePath), page.slug])
15
+ options.documents.flatMap((page) => [
16
+ [path.resolve(page.sourcePath), page.slug],
17
+ ...options.virtualPaths ? [[path.resolve(root, `${page.slug}.mdx`), page.slug]] : []
18
+ ])
14
19
  );
15
20
  const routeCounts = /* @__PURE__ */ new Map();
16
21
  for (const page of options.documents)
@@ -48,7 +53,7 @@ function createDocumentLinkResolver(options) {
48
53
  if ((routeCounts.get(slug) ?? 0) > 1)
49
54
  fail("the destination has an ambiguous documentation route.");
50
55
  const route = [
51
- "/docs",
56
+ options.basePath ?? "/docs",
52
57
  options.routePrefix && encodeURIComponent(options.routePrefix),
53
58
  ...slug.split("/").map(encodeURIComponent)
54
59
  ].filter(Boolean).join("/");
@@ -0,0 +1,75 @@
1
+ // src/project/localization.ts
2
+ import path from "path";
3
+ function getLocalizedProject(project, locale) {
4
+ const selected = project.localization?.locales.find(
5
+ (entry) => entry.path === locale
6
+ );
7
+ if (!selected) throw new Error(`Unknown documentation language: ${locale}`);
8
+ return {
9
+ ...project,
10
+ locale: selected,
11
+ config: { ...project.config, lang: selected.code },
12
+ sources: project.sources.map((source) => {
13
+ const primary = source.localization?.docs[project.localization.defaultLocale] ?? source.fallbackDocsDir ?? source.docsDir;
14
+ const translated = source.localization?.docs[selected.code] ?? (!source.localization && !source.version && selected.folder ? `locale/${selected.folder}/docs` : void 0);
15
+ const isPrimary = selected.code === project.localization.defaultLocale;
16
+ return {
17
+ ...source,
18
+ docsDir: isPrimary ? primary : translated ?? primary,
19
+ fallbackDocsDir: isPrimary ? void 0 : primary,
20
+ fallbackOnly: !isPrimary && !translated,
21
+ basePath: `/${selected.path}/docs`
22
+ };
23
+ })
24
+ };
25
+ }
26
+ function getContentSources(project) {
27
+ return project.localization && !project.locale ? project.localization.locales.flatMap(
28
+ (locale) => getLocalizedProject(project, locale.path).sources
29
+ ) : project.sources;
30
+ }
31
+ function getDocsHref(project, source = project.sources[0], slug = "") {
32
+ const base = source.basePath ?? (project.localization ? `/${project.localization.locales.find((entry) => entry.code === project.localization.defaultLocale).path}/docs` : "/docs");
33
+ return [
34
+ base,
35
+ source.routePrefix,
36
+ ...slug.split("/").filter(Boolean).map(encodeURIComponent)
37
+ ].filter(Boolean).join("/");
38
+ }
39
+ function getLanguageLinks(project, source, slug = "") {
40
+ if (!project.localization) return [];
41
+ const visible = new Set(
42
+ (project.sources[0]?.localization?.locales ?? project.localization.locales).map((locale) => locale.code)
43
+ );
44
+ for (const locale of source.localization?.locales ?? [])
45
+ visible.add(locale.code);
46
+ if (project.locale) visible.add(project.locale.code);
47
+ return project.localization.locales.filter((locale) => visible.has(locale.code)).map((locale) => {
48
+ const view = getLocalizedProject(project, locale.path);
49
+ return {
50
+ code: locale.code,
51
+ label: source.localization?.locales.find(
52
+ (entry) => entry.code === locale.code
53
+ )?.label ?? locale.label,
54
+ href: getDocsHref(
55
+ view,
56
+ view.sources.find((entry) => entry.id === source.id),
57
+ slug
58
+ )
59
+ };
60
+ });
61
+ }
62
+ function isFallbackPage(project, source, sourcePath) {
63
+ return !!source.fallbackDocsDir && !path.relative(
64
+ path.resolve(project.rootDir, source.fallbackDocsDir),
65
+ sourcePath
66
+ ).startsWith("..");
67
+ }
68
+
69
+ export {
70
+ getLocalizedProject,
71
+ getContentSources,
72
+ getDocsHref,
73
+ getLanguageLinks,
74
+ isFallbackPage
75
+ };