@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,272 @@
1
+ import { existsSync, realpathSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join, relative } from "node:path";
4
+
5
+ import {
6
+ addServerHandler,
7
+ addServerImports,
8
+ addTypeTemplate,
9
+ createResolver,
10
+ defineNuxtModule,
11
+ extendPages,
12
+ } from "@nuxt/kit";
13
+ import { createJiti } from "jiti";
14
+
15
+ import {
16
+ FRAMEWORK_ROUTE_NAME,
17
+ frameworkPathOf,
18
+ frameworkRoutePath,
19
+ isUnprefixedDocsPath,
20
+ keepsLayerSitemap,
21
+ type FrameworkUrlsRuntimeConfig,
22
+ type ScannedHandler,
23
+ } from "./utils";
24
+
25
+ export type { FrameworkUrlsRuntimeConfig };
26
+
27
+ /** `frameworkUrls` in `nuxt.config.ts`. */
28
+ export interface FrameworkUrlsOptions {
29
+ /**
30
+ * Serves every docs page at `/docs/<framework>/<page>`, once for each of
31
+ * `docsTheme.frameworks`, and builds each of them. Off by default.
32
+ */
33
+ enabled?: boolean;
34
+ }
35
+
36
+ // For `nuxt.config.ts`. The type of `useRuntimeConfig().public.docsFrameworkUrls`
37
+ // is a type template instead, written in `setup`: Nuxt leaves this file out of
38
+ // the app and server contexts, and `useRuntimeConfig()` reads `nuxt/schema`.
39
+ declare module "@nuxt/schema" {
40
+ interface NuxtConfig {
41
+ frameworkUrls?: FrameworkUrlsOptions;
42
+ }
43
+ interface NuxtOptions {
44
+ frameworkUrls?: FrameworkUrlsOptions;
45
+ }
46
+ }
47
+
48
+ /** The route the prerenderer asks for the list of docs pages. It's never written to disk. */
49
+ export const ROUTES_SEED = "/__docs-framework-routes";
50
+
51
+ const APP_CONFIG_EXTENSIONS = ["ts", "mts", "js", "mjs"];
52
+
53
+ /** A path with its symlinks resolved, or the path itself when it doesn't exist. */
54
+ function realpathOrSelf(path: string): string {
55
+ try {
56
+ return realpathSync(path);
57
+ } catch {
58
+ return path;
59
+ }
60
+ }
61
+
62
+ interface Layer {
63
+ config: { srcDir?: string; rootDir?: string };
64
+ }
65
+
66
+ /**
67
+ * Reads `docsTheme.frameworks` from the app config files of the app and its
68
+ * layers, the way Nuxt merges them: arrays add up, the app's first. The files
69
+ * run in a sandbox where `defineAppConfig` returns what it's given, so a list
70
+ * imported from another file, like Open Components' `./data/frameworks`, works.
71
+ */
72
+ export async function readFrameworks(
73
+ layers: readonly Layer[],
74
+ alias: Record<string, string>,
75
+ inline: unknown,
76
+ ): Promise<string[]> {
77
+ const jiti = createJiti(import.meta.url, { alias, moduleCache: false, fsCache: false });
78
+ const global = globalThis as { defineAppConfig?: unknown };
79
+ const previous = global.defineAppConfig;
80
+ global.defineAppConfig = <T>(config: T) => config;
81
+ const values: string[] = [];
82
+ const collect = (config: unknown) => {
83
+ const frameworks = (config as { docsTheme?: { frameworks?: unknown } } | undefined)?.docsTheme
84
+ ?.frameworks;
85
+ if (!Array.isArray(frameworks)) return;
86
+ for (const option of frameworks) {
87
+ const value = (option as { value?: unknown } | undefined)?.value;
88
+ if (typeof value === "string" && value && !values.includes(value)) values.push(value);
89
+ }
90
+ };
91
+ try {
92
+ for (const layer of layers) {
93
+ const srcDir = layer.config.srcDir;
94
+ if (!srcDir) continue;
95
+ const file = APP_CONFIG_EXTENSIONS.map((ext) => join(srcDir, `app.config.${ext}`)).find(
96
+ (path) => existsSync(path),
97
+ );
98
+ if (file) collect(await jiti.import(file, { default: true }));
99
+ }
100
+ collect(inline);
101
+ } finally {
102
+ global.defineAppConfig = previous;
103
+ }
104
+ return values;
105
+ }
106
+
107
+ /**
108
+ * Framework URLs: every docs page at `/docs/<framework>/<page>`, rendered from
109
+ * the content page at `/docs/<page>` with only that framework's examples, and
110
+ * prerendered once per framework. Unless `frameworkUrls.enabled` is set, it
111
+ * adds nothing but the server helpers, which work without it too.
112
+ */
113
+ export default defineNuxtModule<FrameworkUrlsOptions>({
114
+ meta: { name: "framework-urls", configKey: "frameworkUrls" },
115
+ defaults: { enabled: false },
116
+ async setup(options, nuxt) {
117
+ const resolver = createResolver(import.meta.url);
118
+ const resolve = (path: string) => resolver.resolve(path);
119
+ const docusDir = dirname(createRequire(import.meta.url).resolve("docus/package.json"));
120
+
121
+ // Auto-imported in Nitro with framework URLs off too, so a site's own
122
+ // sitemap route can call them either way.
123
+ addServerImports([
124
+ { name: "getDocsSitemapEntries", from: resolve("./runtime/server/helpers") },
125
+ { name: "docsPageFrameworks", from: resolve("./runtime/server/helpers") },
126
+ ]);
127
+
128
+ // Types `useRuntimeConfig().public.docsFrameworkUrls` in the app and on the
129
+ // server, with framework URLs off too, so the layer's own files type-check
130
+ // inside every site. Nuxt's generated `PublicRuntimeConfig` lives in
131
+ // `nuxt/schema` and shadows the one in `@nuxt/schema`, so the type goes there.
132
+ const utilsPath = resolve("./utils");
133
+ addTypeTemplate(
134
+ {
135
+ filename: "types/layer-docs-framework-urls.d.ts",
136
+ getContents: ({ nuxt }) => {
137
+ const from = relative(join(nuxt.options.buildDir, "types"), utilsPath).replaceAll(
138
+ "\\",
139
+ "/",
140
+ );
141
+ return [
142
+ `import type { FrameworkUrlsRuntimeConfig } from ${JSON.stringify(from.startsWith(".") ? from : `./${from}`)};`,
143
+ "",
144
+ 'declare module "nuxt/schema" {',
145
+ " interface PublicRuntimeConfig {",
146
+ " docsFrameworkUrls?: FrameworkUrlsRuntimeConfig;",
147
+ " }",
148
+ "}",
149
+ "",
150
+ ].join("\n");
151
+ },
152
+ },
153
+ { nuxt: true, nitro: true },
154
+ );
155
+
156
+ if (!options.enabled) return;
157
+
158
+ const rootDir = nuxt.options.rootDir;
159
+ if ((nuxt.options as { i18n?: { locales?: unknown } }).i18n?.locales) {
160
+ throw new Error(
161
+ "[@uxfront/layer-docs] frameworkUrls doesn't support Docus's i18n locales yet.",
162
+ );
163
+ }
164
+ if (!existsSync(join(rootDir, "content", "docs"))) {
165
+ throw new Error(
166
+ "[@uxfront/layer-docs] frameworkUrls serves the pages in content/docs/, and this app has none.",
167
+ );
168
+ }
169
+
170
+ const frameworks = await readFrameworks(
171
+ nuxt.options._layers,
172
+ nuxt.options.alias,
173
+ (nuxt.options.appConfig as Record<string, unknown>)?.docsTheme
174
+ ? nuxt.options.appConfig
175
+ : undefined,
176
+ );
177
+ if (!frameworks.length) {
178
+ throw new Error(
179
+ "[@uxfront/layer-docs] frameworkUrls needs the frameworks listed in docsTheme.frameworks, in app/app.config.ts.",
180
+ );
181
+ }
182
+
183
+ const runtime: FrameworkUrlsRuntimeConfig = { frameworks };
184
+ nuxt.options.runtimeConfig.public.docsFrameworkUrls = runtime;
185
+ // Docus fills in the site's URL from the environment in its own module.
186
+ nuxt.hook("modules:done", () => {
187
+ const site = (nuxt.options as { site?: { url?: string } }).site;
188
+ if (site?.url) runtime.siteUrl = site.url;
189
+ });
190
+
191
+ extendPages((pages) => {
192
+ pages.push({
193
+ name: FRAMEWORK_ROUTE_NAME,
194
+ path: frameworkRoutePath(frameworks),
195
+ file: resolve("./runtime/page.vue"),
196
+ meta: { layout: "docs" },
197
+ });
198
+ });
199
+
200
+ // Docus's landing page, for an app without its own app/pages/index.vue,
201
+ // renders content/index.md as it is, so its links to docs pages would point
202
+ // at pages that aren't built. The layer's copy puts them under the first
203
+ // framework. Swapped once every module has added its pages.
204
+ const docusLanding = join(docusDir, "app", "templates", "landing.vue");
205
+ nuxt.hook("pages:resolved", (pages) => {
206
+ for (const page of pages) {
207
+ if (page.file && realpathOrSelf(page.file) === realpathOrSelf(docusLanding)) {
208
+ page.file = resolve("./runtime/landing.vue");
209
+ }
210
+ }
211
+ });
212
+
213
+ const sitemapHandler = resolve("./runtime/server/sitemap");
214
+ addServerHandler({ route: "/sitemap.xml", handler: sitemapHandler });
215
+ addServerHandler({ middleware: true, handler: resolve("./runtime/server/raw") });
216
+ addServerHandler({ route: ROUTES_SEED, handler: resolve("./runtime/server/routes") });
217
+
218
+ nuxt.hook("nitro:config", (config) => {
219
+ config.prerender ||= {};
220
+ config.prerender.ignore ||= [];
221
+ // Unprefixed docs pages aren't built: every link points under a framework.
222
+ config.prerender.ignore.push((path: string) => isUnprefixedDocsPath(path, frameworks));
223
+ });
224
+
225
+ // A site's own server/routes/sitemap.xml wins over the layer's, which only
226
+ // replaces Docus's. A handler a module adds shadows a scanned one, so the
227
+ // layer takes its own out when the site has one.
228
+ let ownSitemap = false;
229
+ const removeLayerSitemap = (handlers: { route?: string; handler?: string }[] | undefined) => {
230
+ const index = handlers?.findIndex(
231
+ (handler) => handler.route === "/sitemap.xml" && handler.handler === sitemapHandler,
232
+ );
233
+ if (handlers && index !== undefined && index !== -1) handlers.splice(index, 1);
234
+ };
235
+ nuxt.hook("nitro:build:before", (nitro) => {
236
+ const scanned = (nitro as unknown as { scannedHandlers: ScannedHandler[] }).scannedHandlers;
237
+ ownSitemap = !keepsLayerSitemap(scanned, docusDir, realpathOrSelf);
238
+ if (ownSitemap) removeLayerSitemap(nitro.options.handlers);
239
+ });
240
+
241
+ nuxt.hook("nitro:init", (nitro) => {
242
+ // The prerenderer is a Nitro of its own, built from the original config.
243
+ nitro.hooks.hook("prerender:config", (config) => {
244
+ if (ownSitemap) removeLayerSitemap(config.handlers);
245
+ });
246
+
247
+ // Every docs page × every framework, listed explicitly rather than found by
248
+ // crawling: the seed route answers with the content paths, from the content
249
+ // database, so the list is the same with or without a warm parse cache.
250
+ let routes: Set<string> | undefined;
251
+ nitro.hooks.hook("prerender:routes", (set) => {
252
+ routes = set;
253
+ set.add(ROUTES_SEED);
254
+ });
255
+ nitro.hooks.hook("prerender:generate", (route) => {
256
+ if (route.route !== ROUTES_SEED) return;
257
+ route.skip = true;
258
+ // Docus prerenders with `failOnError: false`, so a failure here would
259
+ // otherwise leave the site without a single docs page, and say nothing.
260
+ if (route.error || !routes || !route.contents) {
261
+ throw new Error(
262
+ `[@uxfront/layer-docs] frameworkUrls couldn't list the docs pages to build: ${route.error?.message ?? "no response"}`,
263
+ );
264
+ }
265
+ const paths = JSON.parse(route.contents) as string[];
266
+ for (const path of paths) {
267
+ for (const framework of frameworks) routes.add(frameworkPathOf(path, framework));
268
+ }
269
+ });
270
+ });
271
+ },
272
+ });
@@ -0,0 +1,57 @@
1
+ <script setup lang="ts">
2
+ // Docus's landing page (docus/app/templates/landing.vue), which renders
3
+ // content/index.md at `/` for an app without its own app/pages/index.vue. With
4
+ // framework URLs on, its links to docs pages, from markdown links and component
5
+ // props like `:u-button{to}` alike, go under the first framework, since
6
+ // unprefixed docs pages aren't built.
7
+ //
8
+ // Upgrading Docus: this copies Docus 5.13.0's app/templates/landing.vue.
9
+ // When you raise the `docus` range in package.json, diff that file against
10
+ // this one, carry its changes over, and run `pnpm test:build`.
11
+ import { useFrameworkRoute } from "../../../app/internal/frameworkRoute";
12
+ import { prefixBodyLinks, type MinimarkBody } from "../utils";
13
+
14
+ interface LandingPage {
15
+ title?: string;
16
+ description?: string;
17
+ body?: MinimarkBody;
18
+ seo?: { title?: string; description?: string; ogImage?: string };
19
+ [key: string]: unknown;
20
+ }
21
+
22
+ const route = useRoute();
23
+ const { values, linkFramework } = useFrameworkRoute();
24
+ const query = queryCollection as unknown as (collection: string) => {
25
+ path: (path: string) => { first: () => Promise<LandingPage | null> };
26
+ };
27
+
28
+ const { data: page } = await useAsyncData("landing", async () => {
29
+ const landing = await query("landing").path(route.path).first();
30
+ if (!landing || !linkFramework.value) return landing;
31
+ return { ...landing, body: prefixBodyLinks(landing.body, linkFramework.value, values) };
32
+ });
33
+ if (!page.value) {
34
+ throw createError({ statusCode: 404, statusMessage: "Page not found", fatal: true });
35
+ }
36
+
37
+ const title = page.value.seo?.title || page.value.title;
38
+ const description = page.value.seo?.description || page.value.description;
39
+
40
+ useSeo({
41
+ title,
42
+ description,
43
+ type: "website",
44
+ ogImage: page.value.seo?.ogImage,
45
+ });
46
+
47
+ if (!page.value.seo?.ogImage) {
48
+ defineOgImage("Landing", {
49
+ title: title?.slice(0, 60),
50
+ description: formatOgDescription(title, description),
51
+ });
52
+ }
53
+ </script>
54
+
55
+ <template>
56
+ <ContentRenderer v-if="page" :value="page" />
57
+ </template>
@@ -0,0 +1,211 @@
1
+ <script setup lang="ts">
2
+ // Docus's docs page (docus/app/pages/[[lang]]/[...slug].vue), for
3
+ // `/docs/<framework>/<page>`: it renders the content page at `/docs/<page>`,
4
+ // with only that framework's examples in the page data, links and breadcrumbs
5
+ // under the framework, and the head tags for the frameworks the page covers.
6
+ //
7
+ // Upgrading Docus: this copies Docus 5.13.0's app/pages/[[lang]]/[...slug].vue.
8
+ // When you raise the `docus` range in package.json, diff that file against
9
+ // this one, carry its changes over, and run `pnpm test:build`.
10
+ import { useFrameworkRoute } from "../../../app/internal/frameworkRoute";
11
+ import {
12
+ absoluteUrl,
13
+ contentPathOf,
14
+ findHeadline,
15
+ frameworkPathOf,
16
+ pageFrameworks,
17
+ prefixPageLinks,
18
+ trimPageBody,
19
+ type MinimarkBody,
20
+ type NavigationItem,
21
+ } from "../utils";
22
+
23
+ definePageMeta({
24
+ layout: "docs",
25
+ });
26
+
27
+ interface DocsPage {
28
+ path: string;
29
+ title: string;
30
+ description?: string;
31
+ stem?: string;
32
+ extension?: string;
33
+ body?: MinimarkBody;
34
+ seo?: { title?: string; description?: string };
35
+ links?: { to?: unknown; [key: string]: unknown }[];
36
+ modifiedAt?: string;
37
+ [key: string]: unknown;
38
+ }
39
+
40
+ const route = useRoute();
41
+ const { t } = useDocusI18n();
42
+ const { isOpen } = useAssistant();
43
+ const appConfig = useAppConfig();
44
+ const site = useSiteConfig();
45
+ const navigation = inject<Ref<NavigationItem[] | null>>("navigation");
46
+ const { values } = useFrameworkRoute();
47
+
48
+ const framework = String(route.params.framework);
49
+ const path = contentPathOf(route.params.slug as string[] | undefined);
50
+ const query = queryCollection as unknown as (collection: string) => {
51
+ path: (path: string) => { first: () => Promise<DocsPage | null> };
52
+ };
53
+ const surroundings = queryCollectionItemSurroundings as unknown as (
54
+ collection: string,
55
+ path: string,
56
+ options: { fields: string[] },
57
+ ) => Promise<({ path: string } | null)[]>;
58
+
59
+ const [{ data }, { data: surround }] = await Promise.all([
60
+ useAsyncData(`docs-framework-${route.path}`, async () => {
61
+ const page = await query("docs").path(path).first();
62
+ if (!page) return null;
63
+ // Coverage comes from the whole page, and the data keeps one framework's
64
+ // slots. The frontmatter's links, shown in the page header, keep the framework.
65
+ return {
66
+ covers: pageFrameworks(page.body, values),
67
+ page: {
68
+ ...page,
69
+ body: trimPageBody(page.body, framework, values),
70
+ links: prefixPageLinks(page.links, framework, values),
71
+ },
72
+ };
73
+ }),
74
+ useAsyncData(`docs-framework-${route.path}-surround`, async () => {
75
+ const items = await surroundings("docs", path, { fields: ["description"] });
76
+ return items.map((item) => item && { ...item, path: frameworkPathOf(item.path, framework) });
77
+ }),
78
+ ]);
79
+
80
+ if (!data.value) {
81
+ throw createError({ statusCode: 404, statusMessage: "Page not found", fatal: true });
82
+ }
83
+
84
+ const page = computed(() => data.value!.page);
85
+ const title = page.value.seo?.title || page.value.title;
86
+ const description = page.value.seo?.description || page.value.description;
87
+
88
+ const headline = ref(findHeadline(navigation?.value, path));
89
+ watch(
90
+ () => navigation?.value,
91
+ () => {
92
+ headline.value = findHeadline(navigation?.value, path) || headline.value;
93
+ },
94
+ );
95
+
96
+ const breadcrumbs = computed(() =>
97
+ findPageBreadcrumbs(navigation?.value ?? undefined, path)?.map((item) => ({
98
+ ...item,
99
+ path: frameworkPathOf(item.path, framework),
100
+ })),
101
+ );
102
+
103
+ useSeo({
104
+ title,
105
+ description,
106
+ type: "article",
107
+ modifiedAt: page.value.modifiedAt,
108
+ breadcrumbs,
109
+ });
110
+
111
+ // A covered page is canonical at its own URL, which `useSeo` sets, and names
112
+ // its versions under the other frameworks that cover it. An uncovered one
113
+ // shows another framework's examples, so it stays out of search results, and
114
+ // its canonical is the first framework that covers it.
115
+ const covers = data.value.covers;
116
+ const urlFor = (value: string) => absoluteUrl(site.url, frameworkPathOf(path, value));
117
+ if (covers.includes(framework)) {
118
+ useHead({
119
+ link: covers
120
+ .filter((value) => value !== framework)
121
+ .map((value) => ({ rel: "alternate", href: urlFor(value), key: `alternate-${value}` })),
122
+ });
123
+ } else {
124
+ useSeoMeta({ robots: "noindex, follow" });
125
+ useHead({ link: [{ rel: "canonical", href: urlFor(covers[0] ?? values[0] ?? framework) }] });
126
+ }
127
+
128
+ defineOgImage("Docs", {
129
+ headline: headline.value,
130
+ title: title?.slice(0, 60),
131
+ description: formatOgDescription(title, description),
132
+ });
133
+
134
+ const github = computed(() => (appConfig.github ? appConfig.github : null));
135
+
136
+ const editLink = computed(() => {
137
+ if (!github.value) {
138
+ return;
139
+ }
140
+
141
+ return [
142
+ github.value.url,
143
+ "edit",
144
+ github.value.branch,
145
+ github.value.rootDir,
146
+ "content",
147
+ `${page.value.stem}.${page.value.extension}`,
148
+ ]
149
+ .filter(Boolean)
150
+ .join("/");
151
+ });
152
+
153
+ // The page's markdown, which the layer serves at the framework's path too.
154
+ addPrerenderPath(`/raw${route.path}.md`);
155
+ </script>
156
+
157
+ <template>
158
+ <UPage v-if="page" :ui="isOpen ? { center: 'lg:col-span-10' } : undefined">
159
+ <UPageHeader
160
+ :title="page.title"
161
+ :description="page.description"
162
+ :headline="headline"
163
+ :ui="{
164
+ wrapper: 'flex-row items-center flex-wrap justify-between',
165
+ }"
166
+ >
167
+ <template #links>
168
+ <UButton v-for="(link, index) in page.links" :key="index" size="sm" v-bind="link" />
169
+
170
+ <DocsPageHeaderLinks />
171
+ </template>
172
+ </UPageHeader>
173
+
174
+ <UPageBody>
175
+ <ContentRenderer v-if="page" :value="page" />
176
+
177
+ <USeparator v-if="github">
178
+ <div class="flex items-center gap-2 text-sm text-muted">
179
+ <UButton
180
+ variant="link"
181
+ color="neutral"
182
+ :to="editLink"
183
+ target="_blank"
184
+ icon="i-lucide-pen"
185
+ :ui="{ leadingIcon: 'size-4' }"
186
+ >
187
+ {{ t("docs.edit") }}
188
+ </UButton>
189
+ <template v-if="github?.url">
190
+ <span>{{ t("common.or") }}</span>
191
+ <UButton
192
+ variant="link"
193
+ color="neutral"
194
+ :to="`${github.url}/issues/new/choose`"
195
+ target="_blank"
196
+ icon="i-lucide-alert-circle"
197
+ :ui="{ leadingIcon: 'size-4' }"
198
+ >
199
+ {{ t("docs.report") }}
200
+ </UButton>
201
+ </template>
202
+ </div>
203
+ </USeparator>
204
+ <UContentSurround :surround="surround" />
205
+ </UPageBody>
206
+
207
+ <template v-if="!isOpen" #right>
208
+ <DocsAsideRight :page="page" />
209
+ </template>
210
+ </UPage>
211
+ </template>
@@ -0,0 +1,49 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import { queryCollection, useRuntimeConfig } from "#imports";
4
+
5
+ import {
6
+ pageFrameworks,
7
+ sitemapEntries,
8
+ type DocsSitemapEntry,
9
+ type MinimarkBody,
10
+ type SitemapPage,
11
+ } from "../../utils";
12
+
13
+ export type { DocsSitemapEntry };
14
+
15
+ /**
16
+ * The frameworks a docs page covers, in the order of `frameworks`: those that
17
+ * every `::framework-switcher` on it has a slot for. A page with no switcher
18
+ * covers them all.
19
+ */
20
+ export function docsPageFrameworks(
21
+ page: { body?: MinimarkBody | null } | null | undefined,
22
+ frameworks: readonly string[],
23
+ ): string[] {
24
+ return pageFrameworks(page?.body, frameworks);
25
+ }
26
+
27
+ /**
28
+ * The sitemap's entries, as paths: each docs page once for each framework it
29
+ * covers with framework URLs on, or once at its own path with them off. Pages
30
+ * with `sitemap: false` and navigation-only paths are left out, and
31
+ * `modifiedAt` sets `lastmod`. The landing page, `/`, comes last when Docus
32
+ * renders it.
33
+ */
34
+ export async function getDocsSitemapEntries(event: H3Event): Promise<DocsSitemapEntry[]> {
35
+ const frameworks = useRuntimeConfig(event).public.docsFrameworkUrls?.frameworks ?? [];
36
+ const query = queryCollection as unknown as (
37
+ event: H3Event,
38
+ collection: string,
39
+ ) => { all: () => Promise<SitemapPage[]> };
40
+ const pages: SitemapPage[] = [];
41
+ for (const collection of ["docs", "landing"]) {
42
+ try {
43
+ pages.push(...(await query(event, collection).all()));
44
+ } catch {
45
+ // Docus defines `landing` only when the app has no app/pages/index.vue.
46
+ }
47
+ }
48
+ return sitemapEntries(pages, frameworks);
49
+ }
@@ -0,0 +1,30 @@
1
+ import { createError, defineEventHandler, setResponseHeader, useRuntimeConfig } from "#imports";
2
+
3
+ import { rawContentPath } from "../../utils";
4
+
5
+ /**
6
+ * Serves `/raw/docs/<framework>/<page>.md`, the markdown Docus links from each
7
+ * page, with Nuxt Content's `/raw/docs/<page>.md`. The markdown holds every
8
+ * framework's examples. Nitro's router matches the path the request came in
9
+ * with, so the middleware asks for the content path itself rather than
10
+ * rewriting the URL.
11
+ */
12
+ export default defineEventHandler(async (event) => {
13
+ const frameworks = useRuntimeConfig(event).public.docsFrameworkUrls?.frameworks ?? [];
14
+ const path = rawContentPath(event.node.req.url ?? "", frameworks);
15
+ if (!path) return undefined;
16
+ try {
17
+ const markdown = await event.$fetch<string>(path, { responseType: "text" });
18
+ setResponseHeader(event, "content-type", "text/markdown; charset=utf-8");
19
+ return markdown;
20
+ } catch (error) {
21
+ const statusCode =
22
+ error &&
23
+ typeof error === "object" &&
24
+ "statusCode" in error &&
25
+ typeof error.statusCode === "number"
26
+ ? error.statusCode
27
+ : 500;
28
+ throw createError({ statusCode, statusMessage: statusCode === 404 ? "Page not found" : "" });
29
+ }
30
+ });
@@ -0,0 +1,26 @@
1
+ // h3's helpers come from h3: Nuxt's typed route list loads this file in the app
2
+ // context too, where `#imports` doesn't have them.
3
+ import { createError, defineEventHandler } from "h3";
4
+
5
+ import { queryCollection } from "#imports";
6
+
7
+ import { isNavigationPath } from "../../utils";
8
+
9
+ /**
10
+ * The content paths of every docs page, for the prerenderer, which builds each
11
+ * of them once per framework. It answers only while prerendering.
12
+ */
13
+ export default defineEventHandler(async (event) => {
14
+ if (!import.meta.prerender) throw createError({ statusCode: 404 });
15
+ const query = queryCollection as unknown as (
16
+ event: unknown,
17
+ collection: string,
18
+ ) => { select: (field: "path") => { all: () => Promise<{ path?: string }[]> } };
19
+ const pages = await query(event, "docs").select("path").all();
20
+ return pages
21
+ .map((page) => page.path)
22
+ .filter(
23
+ (path): path is string =>
24
+ !!path && (path === "/docs" || path.startsWith("/docs/")) && !isNavigationPath(path),
25
+ );
26
+ });
@@ -0,0 +1,19 @@
1
+ // h3's helpers come from h3: Nuxt's typed route list loads this file in the app
2
+ // context too, where `#imports` doesn't have them.
3
+ import { defineEventHandler, setResponseHeader } from "h3";
4
+
5
+ import { useRuntimeConfig } from "#imports";
6
+
7
+ import { sitemapXml } from "../../utils";
8
+ import { getDocsSitemapEntries } from "./helpers";
9
+
10
+ /**
11
+ * `/sitemap.xml`, with framework URLs on, in place of Docus's: each docs page
12
+ * once for each framework it covers. A site's own `server/routes/sitemap.xml`
13
+ * replaces this one, and can call `getDocsSitemapEntries` for the same list.
14
+ */
15
+ export default defineEventHandler(async (event) => {
16
+ const { siteUrl } = useRuntimeConfig(event).public.docsFrameworkUrls ?? {};
17
+ setResponseHeader(event, "content-type", "application/xml");
18
+ return sitemapXml(await getDocsSitemapEntries(event), siteUrl);
19
+ });