@uxfront/layer-docs 0.8.4 → 0.9.1

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,418 @@
1
+ /**
2
+ * The pure side of framework URLs, shared by the module, the app and the server
3
+ * routes: the URL shape, which frameworks a page covers, and the page data for
4
+ * one framework. Nothing here touches Nuxt, so the tests call it directly.
5
+ */
6
+
7
+ /** The name of the route that serves `/docs/<framework>/<page>`. */
8
+ export const FRAMEWORK_ROUTE_NAME = "docs-framework";
9
+
10
+ /** A node of a page body in Nuxt Content's minimark format: text, or `[tag, props, ...children]`. */
11
+ export type MinimarkNode = string | MinimarkElement;
12
+ export type MinimarkElement = [string, Record<string, unknown>, ...MinimarkNode[]];
13
+
14
+ /** A page body, as Nuxt Content stores it. */
15
+ export interface MinimarkBody {
16
+ type?: string;
17
+ value?: MinimarkNode[];
18
+ toc?: Toc;
19
+ [key: string]: unknown;
20
+ }
21
+
22
+ interface TocLink {
23
+ id: string;
24
+ children?: TocLink[];
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ interface Toc {
29
+ links?: TocLink[];
30
+ [key: string]: unknown;
31
+ }
32
+
33
+ /**
34
+ * What the module passes to the app and the server at runtime, with framework
35
+ * URLs on, as `useRuntimeConfig().public.docsFrameworkUrls`.
36
+ */
37
+ export interface FrameworkUrlsRuntimeConfig {
38
+ /** The values of `docsTheme.frameworks`, in order, as the build read them. */
39
+ frameworks: string[];
40
+ /** The site's URL, for the absolute URLs in the sitemap. */
41
+ siteUrl?: string;
42
+ }
43
+
44
+ /** A navigation item, as Nuxt Content builds them. */
45
+ export interface NavigationItem {
46
+ title: string;
47
+ path: string;
48
+ stem?: string;
49
+ children?: NavigationItem[];
50
+ [key: string]: unknown;
51
+ }
52
+
53
+ const SWITCHER_TAGS = new Set(["framework-switcher", "FrameworkSwitcher"]);
54
+ const LINK_PROPS = ["href", "to"];
55
+
56
+ /** The route path the layer registers: only the framework values match the segment. */
57
+ export function frameworkRoutePath(frameworks: readonly string[]): string {
58
+ const values = frameworks.map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
59
+ return `/docs/:framework(${values.join("|")})/:slug(.*)*`;
60
+ }
61
+
62
+ /** The content path a framework route renders: `/docs/<page>`. */
63
+ export function contentPathOf(slug: string | readonly string[] | undefined): string {
64
+ const segments = (Array.isArray(slug) ? slug : [slug]).filter(Boolean);
65
+ return segments.length ? `/docs/${segments.join("/")}` : "/docs";
66
+ }
67
+
68
+ /** The framework URL of a content path: `/docs/<page>` becomes `/docs/<framework>/<page>`. */
69
+ export function frameworkPathOf(contentPath: string, framework: string): string {
70
+ if (contentPath === "/docs") return `/docs/${framework}`;
71
+ return `/docs/${framework}${contentPath.slice("/docs".length)}`;
72
+ }
73
+
74
+ /**
75
+ * Puts the framework into a same-site link to a docs page: `/docs/<page>`
76
+ * becomes `/docs/<framework>/<page>`, with its query and hash. A link that
77
+ * already has a framework prefix, `/docs` itself, and any other link stay as
78
+ * they are.
79
+ */
80
+ export function prefixDocsPath<T>(link: T, framework: string, frameworks: readonly string[]): T {
81
+ if (typeof link !== "string" || !link.startsWith("/docs/")) return link;
82
+ const rest = link.slice("/docs/".length);
83
+ const first = rest.split(/[/?#]/, 1)[0] ?? "";
84
+ if (!first || frameworks.includes(first)) return link;
85
+ return `/docs/${framework}/${rest}` as T;
86
+ }
87
+
88
+ /** The same, for every path in a navigation tree. */
89
+ export function prefixNavigation<T extends NavigationItem>(
90
+ items: readonly T[] | null | undefined,
91
+ framework: string,
92
+ frameworks: readonly string[],
93
+ ): T[] {
94
+ return (items ?? []).map((item) => ({
95
+ ...item,
96
+ path: prefixDocsPath(item.path, framework, frameworks),
97
+ ...(item.children && {
98
+ children: prefixNavigation(item.children, framework, frameworks),
99
+ }),
100
+ }));
101
+ }
102
+
103
+ /**
104
+ * Whether the prerenderer should leave a path out: an unprefixed docs page
105
+ * like `/docs/<page>` or its payload, which a site with framework URLs serves
106
+ * only under a framework.
107
+ */
108
+ export function isUnprefixedDocsPath(path: string, frameworks: readonly string[]): boolean {
109
+ if (!path.startsWith("/docs/")) return false;
110
+ const first = path.slice("/docs/".length).split(/[/?#]/, 1)[0] ?? "";
111
+ return !frameworks.includes(first);
112
+ }
113
+
114
+ /**
115
+ * The path of the markdown Nuxt Content serves for a framework path:
116
+ * `/raw/docs/react/a.md` becomes `/raw/docs/a.md`, and `/raw/docs/react.md`
117
+ * `/raw/docs.md`. Any other path gives `undefined`.
118
+ */
119
+ export function rawContentPath(url: string, frameworks: readonly string[]): string | undefined {
120
+ if (!url.startsWith("/raw/docs/")) return undefined;
121
+ const rest = url.slice("/raw/docs/".length);
122
+ const framework = rest.split(/[/.?#]/, 1)[0] ?? "";
123
+ if (!frameworks.includes(framework)) return undefined;
124
+ const after = rest.slice(framework.length);
125
+ const [path = ""] = after.split(/[?#]/, 1);
126
+ if (!path.endsWith(".md") || !(path.startsWith("/") || path === ".md")) return undefined;
127
+ return `/raw/docs${after}`;
128
+ }
129
+
130
+ function isElement(node: MinimarkNode | undefined): node is MinimarkElement {
131
+ return Array.isArray(node) && typeof node[0] === "string";
132
+ }
133
+
134
+ /** The slot a `<template>` child of a switcher fills, as `react` for `#react`. */
135
+ function slotOf(node: MinimarkNode): string | undefined {
136
+ if (!isElement(node) || node[0] !== "template") return undefined;
137
+ for (const key of Object.keys(node[1] ?? {})) {
138
+ if (key.startsWith("v-slot:")) return key.slice("v-slot:".length);
139
+ if (key.startsWith("#")) return key.slice(1);
140
+ }
141
+ return undefined;
142
+ }
143
+
144
+ function childrenOf(node: MinimarkElement): MinimarkNode[] {
145
+ return node.slice(2) as MinimarkNode[];
146
+ }
147
+
148
+ function switchersIn(nodes: readonly MinimarkNode[] | undefined): MinimarkElement[] {
149
+ const found: MinimarkElement[] = [];
150
+ const visit = (node: MinimarkNode) => {
151
+ if (!isElement(node)) return;
152
+ if (SWITCHER_TAGS.has(node[0])) found.push(node);
153
+ childrenOf(node).forEach(visit);
154
+ };
155
+ (nodes ?? []).forEach(visit);
156
+ return found;
157
+ }
158
+
159
+ /**
160
+ * The frameworks a page covers, in the order of `frameworks`: those that every
161
+ * `::framework-switcher` on it has a slot for. A page with no switcher covers
162
+ * them all.
163
+ */
164
+ export function pageFrameworks(
165
+ body: MinimarkBody | null | undefined,
166
+ frameworks: readonly string[],
167
+ ): string[] {
168
+ const switchers = switchersIn(body?.value);
169
+ return frameworks.filter((framework) =>
170
+ switchers.every((switcher) =>
171
+ childrenOf(switcher).some((child) => slotOf(child) === framework),
172
+ ),
173
+ );
174
+ }
175
+
176
+ /**
177
+ * The slot `FrameworkSwitcher` shows for a framework: its own, or the first
178
+ * one the switcher has, in the order of `frameworks`.
179
+ */
180
+ function shownSlot(
181
+ switcher: MinimarkElement,
182
+ framework: string,
183
+ frameworks: readonly string[],
184
+ ): string | undefined {
185
+ const slots = new Set(childrenOf(switcher).map(slotOf));
186
+ if (slots.has(framework)) return framework;
187
+ return frameworks.find((value) => slots.has(value));
188
+ }
189
+
190
+ function trimNode(
191
+ node: MinimarkNode,
192
+ framework: string,
193
+ frameworks: readonly string[],
194
+ trimSlots = true,
195
+ ): MinimarkNode | undefined {
196
+ if (!isElement(node)) return node;
197
+ const [tag, props, ...children] = node;
198
+
199
+ let kept = children;
200
+ if (trimSlots && SWITCHER_TAGS.has(tag)) {
201
+ const shown = shownSlot(node, framework, frameworks);
202
+ kept = children.filter((child) => {
203
+ const slot = slotOf(child);
204
+ return slot === undefined || slot === shown;
205
+ });
206
+ }
207
+
208
+ const nextProps = { ...props };
209
+ for (const key of LINK_PROPS) {
210
+ if (key in nextProps) nextProps[key] = prefixDocsPath(nextProps[key], framework, frameworks);
211
+ }
212
+
213
+ const nextChildren = kept
214
+ .map((child) => trimNode(child, framework, frameworks, trimSlots))
215
+ .filter((child): child is MinimarkNode => child !== undefined);
216
+ return [tag, nextProps, ...nextChildren];
217
+ }
218
+
219
+ function idsIn(nodes: readonly MinimarkNode[]): Set<string> {
220
+ const ids = new Set<string>();
221
+ const visit = (node: MinimarkNode) => {
222
+ if (!isElement(node)) return;
223
+ const id = node[1]?.id;
224
+ if (typeof id === "string") ids.add(id);
225
+ childrenOf(node).forEach(visit);
226
+ };
227
+ nodes.forEach(visit);
228
+ return ids;
229
+ }
230
+
231
+ function filterToc(links: readonly TocLink[], ids: Set<string>): TocLink[] {
232
+ return links
233
+ .filter((link) => ids.has(link.id))
234
+ .map((link) => (link.children ? { ...link, children: filterToc(link.children, ids) } : link));
235
+ }
236
+
237
+ /**
238
+ * A page body for one framework: each `::framework-switcher` keeps only the
239
+ * slot `FrameworkSwitcher` shows, same-site links to docs pages get the
240
+ * framework's prefix, and the table of contents drops the headings that went
241
+ * with the other slots.
242
+ */
243
+ export function trimPageBody<T extends MinimarkBody | null | undefined>(
244
+ body: T,
245
+ framework: string,
246
+ frameworks: readonly string[],
247
+ ): T {
248
+ if (!body || !Array.isArray(body.value)) return body;
249
+ const value = body.value
250
+ .map((node) => trimNode(node, framework, frameworks))
251
+ .filter((node): node is MinimarkNode => node !== undefined);
252
+ const next: MinimarkBody = { ...body, value };
253
+ if (body.toc?.links) {
254
+ next.toc = { ...body.toc, links: filterToc(body.toc.links, idsIn(value)) };
255
+ }
256
+ return next as T;
257
+ }
258
+
259
+ /**
260
+ * A page body with its same-site links to docs pages under `framework`, and
261
+ * its switchers left whole, for a page outside the docs, like Docus's landing
262
+ * page, which links to the docs under the first framework.
263
+ */
264
+ export function prefixBodyLinks<T extends MinimarkBody | null | undefined>(
265
+ body: T,
266
+ framework: string,
267
+ frameworks: readonly string[],
268
+ ): T {
269
+ if (!body || !Array.isArray(body.value)) return body;
270
+ const value = body.value
271
+ .map((node) => trimNode(node, framework, frameworks, false))
272
+ .filter((node): node is MinimarkNode => node !== undefined);
273
+ return { ...body, value } as T;
274
+ }
275
+
276
+ /** A page's frontmatter `links`, with each `to` under `framework`. */
277
+ export function prefixPageLinks<T extends { to?: unknown }>(
278
+ links: readonly T[] | null | undefined,
279
+ framework: string,
280
+ frameworks: readonly string[],
281
+ ): T[] | undefined {
282
+ return links?.map((link) => ({ ...link, to: prefixDocsPath(link.to, framework, frameworks) }));
283
+ }
284
+
285
+ /**
286
+ * The title of the section a page sits in, as Nuxt Content's
287
+ * `findPageHeadline` finds it, for the headline above the page's title.
288
+ */
289
+ export function findHeadline(
290
+ navigation: readonly NavigationItem[] | null | undefined,
291
+ path: string,
292
+ ): string | undefined {
293
+ for (const link of navigation ?? []) {
294
+ if (!link.children) continue;
295
+ if (link.children.some((child) => child.path === path && !child.stem?.endsWith("/index"))) {
296
+ return link.title;
297
+ }
298
+ const headline = findHeadline(link.children, path);
299
+ if (headline) return headline;
300
+ }
301
+ return undefined;
302
+ }
303
+
304
+ /** An absolute URL on the site, or the path itself when the site has no URL. */
305
+ export function absoluteUrl(siteUrl: string | undefined, path: string): string {
306
+ return siteUrl ? `${siteUrl.replace(/\/+$/, "")}${path}` : path;
307
+ }
308
+
309
+ /** A Nuxt Content path that only holds navigation settings, like `/docs/.navigation`. */
310
+ export function isNavigationPath(path: string): boolean {
311
+ return path.endsWith(".navigation") || path.includes("/.navigation/");
312
+ }
313
+
314
+ /** A docs page, with the fields the sitemap reads. */
315
+ export interface SitemapPage {
316
+ path?: string;
317
+ body?: MinimarkBody | null;
318
+ meta?: Record<string, unknown> | null;
319
+ sitemap?: unknown;
320
+ modifiedAt?: unknown;
321
+ }
322
+
323
+ /** One `<url>` of the sitemap: a path on the site, not an absolute URL. */
324
+ export interface DocsSitemapEntry {
325
+ /** The page's URL path, as `/docs/react/components/button`. */
326
+ loc: string;
327
+ /** The date part of the page's `modifiedAt`, as `2026-11-19`, when it has one. */
328
+ lastmod?: string;
329
+ /** The page's content path, as `/docs/components/button`. */
330
+ path: string;
331
+ }
332
+
333
+ /**
334
+ * The sitemap's entries for a list of pages, by Docus's rules: a page with
335
+ * `sitemap: false` or a navigation-only path is left out, and `modifiedAt`
336
+ * sets `lastmod`. With framework URLs on, each docs page comes once for each
337
+ * framework it covers. Without them, `frameworks` is empty, and each page
338
+ * comes once at its own path.
339
+ */
340
+ export function sitemapEntries(
341
+ pages: readonly SitemapPage[],
342
+ frameworks: readonly string[],
343
+ ): DocsSitemapEntry[] {
344
+ const entries: DocsSitemapEntry[] = [];
345
+ for (const page of pages) {
346
+ const path = page.path || "/";
347
+ const meta = page.meta ?? {};
348
+ if ((meta.sitemap ?? page.sitemap) === false || isNavigationPath(path)) continue;
349
+ const modifiedAt = meta.modifiedAt ?? page.modifiedAt;
350
+ const lastmod = typeof modifiedAt === "string" ? modifiedAt.split("T")[0] : undefined;
351
+ const isDocsPage = path === "/docs" || path.startsWith("/docs/");
352
+ const locs =
353
+ frameworks.length && isDocsPage
354
+ ? pageFrameworks(page.body, frameworks).map((framework) => frameworkPathOf(path, framework))
355
+ : [path];
356
+ for (const loc of locs) entries.push({ loc, path, ...(lastmod && { lastmod }) });
357
+ }
358
+ return entries;
359
+ }
360
+
361
+ const XML_ENTITIES: Record<string, string> = {
362
+ "&": "&amp;",
363
+ "<": "&lt;",
364
+ ">": "&gt;",
365
+ '"': "&quot;",
366
+ "'": "&apos;",
367
+ };
368
+
369
+ function escapeXml(value: string): string {
370
+ return value.replace(/[&<>"']/g, (char) => XML_ENTITIES[char] ?? char);
371
+ }
372
+
373
+ /** The sitemap XML for a list of entries, as Docus writes it. */
374
+ export function sitemapXml(
375
+ entries: readonly DocsSitemapEntry[],
376
+ siteUrl: string | undefined,
377
+ ): string {
378
+ const urls = entries.map(({ loc, lastmod }) =>
379
+ [
380
+ " <url>",
381
+ ` <loc>${escapeXml(absoluteUrl(siteUrl, loc))}</loc>`,
382
+ ...(lastmod ? [` <lastmod>${escapeXml(lastmod)}</lastmod>`] : []),
383
+ " </url>",
384
+ ].join("\n"),
385
+ );
386
+ return [
387
+ '<?xml version="1.0" encoding="UTF-8"?>',
388
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
389
+ ...urls,
390
+ "</urlset>",
391
+ ].join("\n");
392
+ }
393
+
394
+ /** A server handler Nitro found in a `server/routes/` directory. */
395
+ export interface ScannedHandler {
396
+ route?: string;
397
+ handler: string;
398
+ }
399
+
400
+ /**
401
+ * Whether the layer's `/sitemap.xml` should stay: only when no scanned route
402
+ * serves that path outside the Docus package, since a site's own route wins.
403
+ * Docus's own route doesn't count, as the layer's replaces it. `realpath`
404
+ * resolves symlinks, since pnpm can reach Docus through `node_modules/docus`
405
+ * or `node_modules/.pnpm/docus@…`.
406
+ */
407
+ export function keepsLayerSitemap(
408
+ scanned: readonly ScannedHandler[],
409
+ docusDir: string,
410
+ realpath: (path: string) => string,
411
+ ): boolean {
412
+ const docus = realpath(docusDir).replace(/[\\/]+$/, "");
413
+ return !scanned.some((handler) => {
414
+ if (handler.route !== "/sitemap.xml") return false;
415
+ const file = realpath(handler.handler);
416
+ return !(file === docus || file.startsWith(`${docus}/`) || file.startsWith(`${docus}\\`));
417
+ });
418
+ }
package/nuxt.config.ts CHANGED
@@ -19,12 +19,26 @@ const resolver = createResolver(import.meta.url);
19
19
  * sidebar's accordions still find their elements once the prerendered page
20
20
  * hydrates.
21
21
  *
22
+ * Its `framework-urls` module, off unless the app sets
23
+ * `frameworkUrls: { enabled: true }`, serves every docs page at
24
+ * `/docs/<framework>/<page>` and builds it once per framework, with only that
25
+ * framework's examples in it. There the route decides the framework, the select
26
+ * goes to the same page under the new one, links keep it, a page a framework
27
+ * doesn't cover is `noindex` with its canonical on the first that does, and the
28
+ * layer serves `/sitemap.xml` unless the app has its own. `docsPath()` gives the
29
+ * URL of a docs page for links outside the Docus shell, and the auto-imported
30
+ * server helpers `getDocsSitemapEntries` and `docsPageFrameworks` give a site's
31
+ * own sitemap the same pages.
32
+ *
22
33
  * https://nuxt.com/docs/getting-started/layers
23
34
  */
24
35
  export default defineNuxtConfig({
25
36
  extends: ["docus"],
26
37
 
27
- modules: [resolver.resolve("./modules/hydration-ids")],
38
+ modules: [
39
+ resolver.resolve("./modules/hydration-ids"),
40
+ resolver.resolve("./modules/framework-urls"),
41
+ ],
28
42
 
29
43
  content: {
30
44
  build: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxfront/layer-docs",
3
- "version": "0.8.4",
3
+ "version": "0.9.1",
4
4
  "description": "Nuxt layer for UXFront documentation sites: Docus, plus a framework switcher that shows every reader the examples for their framework, and the UXFront header wordmark.",
5
5
  "keywords": [
6
6
  "docs",
@@ -40,7 +40,8 @@
40
40
  "@nuxt/kit": "^4.5.2",
41
41
  "@uxfront/ui": "^0.9.1",
42
42
  "@vueuse/core": "^14.4.0",
43
- "docus": "^5.13.0"
43
+ "docus": "^5.13.0",
44
+ "jiti": "^2.7.0"
44
45
  },
45
46
  "devDependencies": {
46
47
  "nuxt": "^4.5.2",
@@ -52,6 +53,7 @@
52
53
  "vue": "^3.5.0"
53
54
  },
54
55
  "scripts": {
55
- "test": "vitest run"
56
+ "test": "vitest run",
57
+ "test:build": "vitest run --config vitest.build.config.ts"
56
58
  }
57
59
  }