@mdream/nuxt 0.8.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.
package/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Harlan Wilton
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @mdream/nuxt
2
+
3
+ [![npm version][npm-version-src]][npm-version-href]
4
+ [![npm downloads][npm-downloads-src]][npm-downloads-href]
5
+ [![License][license-src]][license-href]
6
+ [![Nuxt][nuxt-src]][nuxt-href]
7
+
8
+ Nuxt module for converting HTML pages to Markdown using [mdream](https://github.com/unjs/mdream).
9
+
10
+ Mdream provides a Nuxt module that enables seamless HTML to Markdown conversion for Nuxt 3 applications.
11
+
12
+ - **🚀 On-Demand Generation**: Access any route with `.md` extension (e.g., `/about` → `/about.md`)
13
+ - **📄 LLMs.txt Generation**: Creates `llms.txt` and `llms-full.txt` artifacts during prerendering
14
+
15
+ ### Installation
16
+
17
+ ```bash
18
+ npm install @mdream/nuxt mdream
19
+ # or
20
+ pnpm add @mdream/nuxt mdream
21
+ # or
22
+ yarn add @mdream/nuxt mdream
23
+ ```
24
+
25
+ ### Usage
26
+
27
+ Add the module to your `nuxt.config.ts`:
28
+
29
+ ```ts
30
+ export default defineNuxtConfig({
31
+ modules: [
32
+ '@mdream/nuxt'
33
+ ],
34
+ })
35
+ ```
36
+
37
+ Done! Add the `.md` to any file path to access markdown.
38
+
39
+ When statically generating your site with `nuxi generate` it will create `llms.txt` artifacts.
40
+
41
+ ## Configuration
42
+
43
+ Configure the module in your `nuxt.config.ts`:
44
+
45
+ ```ts
46
+ export default defineNuxtConfig({
47
+ modules: ['@mdream/nuxt'],
48
+
49
+ mdream: {
50
+ // Enable/disable the module
51
+ enabled: true,
52
+
53
+ // Pass options to mdream
54
+ mdreamOptions: {
55
+ // mdream conversion options
56
+ },
57
+
58
+ // Cache configuration (production only)
59
+ cache: {
60
+ maxAge: 3600, // 1 hour
61
+ swr: true // Stale-while-revalidate
62
+ }
63
+ }
64
+ })
65
+ ```
66
+
67
+ ### Options
68
+
69
+ - `enabled` (boolean): Enable or disable the module. Default: `true`
70
+ - `mdreamOptions` (object): Options passed to mdream's `htmlToMarkdown` function
71
+ - `cache.maxAge` (number): Cache duration in seconds. Default: `3600` (1 hour)
72
+ - `cache.swr` (boolean): Enable stale-while-revalidate. Default: `true`
73
+
74
+ ## Robot Meta Tag Support
75
+
76
+ The module respects the `robots` meta tag. Pages with `noindex` will return a 404 error when accessed as markdown:
77
+
78
+ ```vue
79
+ <script setup>
80
+ useHead({
81
+ meta: [
82
+ { name: 'robots', content: 'noindex' }
83
+ ]
84
+ })
85
+ </script>
86
+ ```
87
+
88
+ ## Static Generation
89
+
90
+ When using `nuxt generate` or static hosting, the module automatically:
91
+
92
+ 1. Generates `.md` files for all pages
93
+ 2. Creates `llms.txt` with page listings
94
+ 3. Creates `llms-full.txt` with full content
95
+
96
+ These files are placed in the `public/` directory and served as static assets.
97
+
98
+ ## License
99
+
100
+ [MIT License](./LICENSE)
101
+
102
+ <!-- Badges -->
103
+ [npm-version-src]: https://img.shields.io/npm/v/@mdream/nuxt/latest.svg?style=flat&colorA=020420&colorB=00DC82
104
+ [npm-version-href]: https://npmjs.com/package/@mdream/nuxt
105
+
106
+ [npm-downloads-src]: https://img.shields.io/npm/dm/@mdream/nuxt.svg?style=flat&colorA=020420&colorB=00DC82
107
+ [npm-downloads-href]: https://npm.chart.dev/@mdream/nuxt
108
+
109
+ [license-src]: https://img.shields.io/npm/l/@mdream/nuxt.svg?style=flat&colorA=020420&colorB=00DC82
110
+ [license-href]: https://npmjs.com/package/@mdream/nuxt
111
+
112
+ [nuxt-src]: https://img.shields.io/badge/Nuxt-020420?logo=nuxt.js
113
+ [nuxt-href]: https://nuxt.com
@@ -0,0 +1,38 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { HTMLToMarkdownOptions } from 'mdream';
3
+
4
+ interface ModuleOptions {
5
+ /**
6
+ * Enable/disable the module
7
+ * @default true
8
+ */
9
+ enabled?: boolean;
10
+ /**
11
+ * Options to pass to mdream htmlToMarkdown function
12
+ */
13
+ mdreamOptions?: HTMLToMarkdownOptions & {
14
+ /**
15
+ * Preset to apply to the htmlToMarkdown function
16
+ */
17
+ preset?: 'minimal';
18
+ };
19
+ /**
20
+ * Cache configuration
21
+ */
22
+ cache?: {
23
+ /**
24
+ * Cache duration in seconds
25
+ * @default 3600 (1 hour)
26
+ */
27
+ maxAge?: number;
28
+ /**
29
+ * Enable stale-while-revalidate
30
+ * @default true
31
+ */
32
+ swr?: boolean;
33
+ };
34
+ }
35
+
36
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
37
+
38
+ export { _default as default };
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@mdream/nuxt",
3
+ "version": "0.8.0",
4
+ "configKey": "mdream",
5
+ "compatibility": {
6
+ "nuxt": "^3.0.0"
7
+ },
8
+ "builder": {
9
+ "@nuxt/module-builder": "1.0.1",
10
+ "unbuild": "3.5.0"
11
+ }
12
+ }
@@ -0,0 +1,178 @@
1
+ import { useNuxt, defineNuxtModule, createResolver, addTypeTemplate, addServerHandler } from '@nuxt/kit';
2
+ import { defu } from 'defu';
3
+ import { useSiteConfig, installNuxtSiteConfig } from 'nuxt-site-config/kit';
4
+ import { join, dirname, relative, resolve } from 'node:path';
5
+ import { mkdir, writeFile } from 'node:fs/promises';
6
+ import { consola } from 'consola';
7
+ import { htmlToMarkdown, generateLlmsTxtArtifacts } from 'mdream';
8
+
9
+ const name = "@mdream/nuxt";
10
+ const version = "0.8.0";
11
+
12
+ const logger = consola.withTag("nuxt-mdream");
13
+ function isIndexable(html) {
14
+ const robotsMatch = html.match(/<meta\s+name=["']robots["']\s+content=["']([^"']+)["']/i);
15
+ if (robotsMatch) {
16
+ const content = robotsMatch[1].toLowerCase();
17
+ return !content.includes("noindex");
18
+ }
19
+ return true;
20
+ }
21
+ function setupPrerenderHandler(config, nuxt = useNuxt()) {
22
+ const pages = [];
23
+ nuxt.hooks.hook("nitro:init", async (nitro) => {
24
+ nitro.hooks.hook("prerender:generate", async (route) => {
25
+ if (!route.fileName?.endsWith(".html") || !route.contents) {
26
+ return;
27
+ }
28
+ if (["/200.html", "/404.html"].includes(route.route)) {
29
+ return;
30
+ }
31
+ const html = route.contents;
32
+ if (!isIndexable(html)) {
33
+ return;
34
+ }
35
+ try {
36
+ const markdown = htmlToMarkdown(html, {
37
+ origin: route.route,
38
+ ...config.mdreamOptions
39
+ });
40
+ const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
41
+ const title = titleMatch ? titleMatch[1].trim() : route.route;
42
+ pages.push({
43
+ url: route.route,
44
+ title,
45
+ markdown
46
+ });
47
+ const mdPath = route.route === "/" ? "/index.md" : `${route.route}.md`;
48
+ const outputPath = join(nitro.options.output.publicDir, mdPath);
49
+ await mkdir(dirname(outputPath), { recursive: true });
50
+ await writeFile(outputPath, markdown, "utf-8");
51
+ } catch (error) {
52
+ logger.warn(`Failed to convert ${route.route} to markdown:`, error);
53
+ }
54
+ });
55
+ nitro.hooks.hook("prerender:done", async () => {
56
+ if (pages.length === 0) {
57
+ return;
58
+ }
59
+ try {
60
+ const processedFiles = pages.map((page) => ({
61
+ title: page.title,
62
+ content: page.markdown,
63
+ url: page.url === "/" ? "/index.md" : `${page.url}.md`
64
+ }));
65
+ const siteConfig = useSiteConfig();
66
+ const artifacts = await generateLlmsTxtArtifacts({
67
+ files: processedFiles,
68
+ generateFull: true,
69
+ siteName: siteConfig.name || siteConfig.url,
70
+ description: siteConfig.description
71
+ });
72
+ if (artifacts.llmsTxt) {
73
+ const llmsTxtPath = join(nitro.options.output.publicDir, "llms.txt");
74
+ await writeFile(llmsTxtPath, artifacts.llmsTxt, "utf-8");
75
+ }
76
+ if (artifacts.llmsFullTxt) {
77
+ const llmsFullTxtPath = join(nitro.options.output.publicDir, "llms-full.txt");
78
+ await writeFile(llmsFullTxtPath, artifacts.llmsFullTxt, "utf-8");
79
+ }
80
+ logger.success(`Generated markdown for ${pages.length} pages`);
81
+ if (artifacts.llmsTxt) {
82
+ logger.info("Generated llms.txt");
83
+ }
84
+ if (artifacts.llmsFullTxt) {
85
+ logger.info("Generated llms-full.txt");
86
+ }
87
+ } catch (error) {
88
+ logger.error("Failed to generate llms.txt artifacts:", error);
89
+ }
90
+ });
91
+ });
92
+ }
93
+
94
+ const module = defineNuxtModule({
95
+ meta: {
96
+ name,
97
+ version,
98
+ configKey: "mdream",
99
+ compatibility: {
100
+ nuxt: "^3.0.0"
101
+ }
102
+ },
103
+ defaults: {
104
+ enabled: true,
105
+ mdreamOptions: {},
106
+ cache: {
107
+ maxAge: 3600,
108
+ // 1 hour
109
+ swr: true
110
+ }
111
+ },
112
+ async setup(options, nuxt) {
113
+ if (!options.enabled) {
114
+ return;
115
+ }
116
+ const resolver = createResolver(import.meta.url);
117
+ await installNuxtSiteConfig();
118
+ const runtimeConfig = {
119
+ enabled: options.enabled,
120
+ mdreamOptions: options.mdreamOptions,
121
+ cache: defu(options.cache, {
122
+ maxAge: 3600,
123
+ swr: true
124
+ })
125
+ };
126
+ nuxt.options.runtimeConfig.mdream = defu(
127
+ nuxt.options.runtimeConfig.mdream,
128
+ runtimeConfig
129
+ );
130
+ addTypeTemplate({
131
+ filename: "module/nuxt-mdream.d.ts",
132
+ getContents: (data) => {
133
+ const typesPath = relative(resolve(data.nuxt.options.rootDir, data.nuxt.options.buildDir, "module"), resolve("runtime/types"));
134
+ const types = ` interface NitroRuntimeHooks {
135
+ 'mdream:markdown': (context: import('${typesPath}').MdreamMarkdownContext) => void | Promise<void>
136
+ }`;
137
+ return `// Generated by nuxt-mdream
138
+
139
+ declare module '@nuxt/schema' {
140
+ interface RuntimeConfig {
141
+ mdream: {
142
+ enabled: boolean
143
+ mdreamOptions: Record<string, any>
144
+ cache: {
145
+ maxAge: number
146
+ swr: boolean
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ declare module 'nitropack/types' {
153
+ ${types}
154
+ }
155
+
156
+ declare module 'nitropack' {
157
+ ${types}
158
+ }
159
+
160
+ export {}
161
+ `;
162
+ }
163
+ }, {
164
+ nitro: true,
165
+ nuxt: true
166
+ });
167
+ addServerHandler({
168
+ middleware: true,
169
+ handler: resolver.resolve("./runtime/server/middleware/mdream")
170
+ });
171
+ const isStatic = nuxt.options.nitro.static || nuxt.options._generate || false;
172
+ if (isStatic || nuxt.options.nitro.prerender?.routes?.length) {
173
+ setupPrerenderHandler(runtimeConfig, nuxt);
174
+ }
175
+ }
176
+ });
177
+
178
+ export { module as default };
@@ -0,0 +1,2 @@
1
+ declare const _default: import("h3").EventHandler<import("h3").EventHandlerRequest, Promise<string | undefined>>;
2
+ export default _default;
@@ -0,0 +1,102 @@
1
+ import { consola } from "consola";
2
+ import { createError, defineEventHandler, getRequestURL, setHeader } from "h3";
3
+ import { htmlToMarkdown } from "mdream";
4
+ import { withMinimalPreset } from "mdream/preset/minimal";
5
+ import { useNitroApp, useRuntimeConfig } from "nitropack/runtime";
6
+ const logger = consola.withTag("nuxt-mdream");
7
+ function isIndexable(html) {
8
+ const robotsMatch = html.match(/<meta\s+name=["']robots["']\s+content=["']([^"']+)["']/i);
9
+ if (robotsMatch) {
10
+ const content = robotsMatch[1].toLowerCase();
11
+ return !content.includes("noindex");
12
+ }
13
+ return true;
14
+ }
15
+ async function convertHtmlToMarkdown(html, url, config, route, title) {
16
+ let options = {
17
+ origin: url,
18
+ ...config.mdreamOptions
19
+ };
20
+ if (config.mdreamOptions?.preset === "minimal") {
21
+ options = withMinimalPreset(options);
22
+ }
23
+ let markdown = htmlToMarkdown(html, options);
24
+ const context = {
25
+ html,
26
+ markdown,
27
+ route,
28
+ title,
29
+ isPrerender: false
30
+ };
31
+ try {
32
+ const nitroApp = useNitroApp();
33
+ if (nitroApp?.hooks) {
34
+ await nitroApp.hooks.callHook("mdream:markdown", context);
35
+ markdown = context.markdown;
36
+ }
37
+ } catch (error) {
38
+ logger.debug("Could not call mdream:markdown hook:", error);
39
+ }
40
+ return markdown;
41
+ }
42
+ export default defineEventHandler(async (event) => {
43
+ const requestUrl = getRequestURL(event);
44
+ let htmlPath = requestUrl.pathname;
45
+ if (!htmlPath.endsWith(".md")) {
46
+ return;
47
+ }
48
+ const config = useRuntimeConfig(event).mdream;
49
+ htmlPath = htmlPath.slice(0, -3);
50
+ if (htmlPath === "/index") {
51
+ htmlPath = "/";
52
+ }
53
+ try {
54
+ const fullUrl = new URL(htmlPath, requestUrl.origin).toString();
55
+ const response = await fetch(fullUrl, {
56
+ headers: {
57
+ // Forward important headers
58
+ "user-agent": event.headers.get("user-agent") || "",
59
+ "accept-language": event.headers.get("accept-language") || ""
60
+ }
61
+ });
62
+ if (!response.ok) {
63
+ throw createError({
64
+ statusCode: response.status,
65
+ statusMessage: response.statusText
66
+ });
67
+ }
68
+ const html = await response.text();
69
+ if (!isIndexable(html)) {
70
+ throw createError({
71
+ statusCode: 404,
72
+ statusMessage: "Page not indexable"
73
+ });
74
+ }
75
+ const titleMatch = html.match(/<title[^>]*>([^<]+)<\/title>/i);
76
+ const title = titleMatch ? titleMatch[1].trim() : htmlPath;
77
+ const markdown = await convertHtmlToMarkdown(
78
+ html,
79
+ requestUrl.origin + htmlPath,
80
+ config,
81
+ htmlPath,
82
+ title
83
+ );
84
+ setHeader(event, "content-type", "text/markdown; charset=utf-8");
85
+ return markdown;
86
+ } catch (error) {
87
+ if (error.statusCode) {
88
+ throw error;
89
+ }
90
+ if (error.status === 404) {
91
+ throw createError({
92
+ statusCode: 404,
93
+ statusMessage: "Page not found"
94
+ });
95
+ }
96
+ logger.error("Failed to generate markdown for", htmlPath, error);
97
+ throw createError({
98
+ statusCode: 500,
99
+ statusMessage: `Failed to generate markdown: ${error.message || "Unknown error"}`
100
+ });
101
+ }
102
+ });
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": "../../../.nuxt/tsconfig.server.json"
3
+ }
@@ -0,0 +1,20 @@
1
+ export interface MdreamPage {
2
+ url: string;
3
+ title: string;
4
+ markdown: string;
5
+ }
6
+ /**
7
+ * Hook context for markdown processing
8
+ */
9
+ export interface MdreamMarkdownContext {
10
+ /** The original HTML content */
11
+ html: string;
12
+ /** The generated markdown content */
13
+ markdown: string;
14
+ /** The route being processed */
15
+ route: string;
16
+ /** The page title extracted from HTML */
17
+ title: string;
18
+ /** Whether this is during prerendering */
19
+ isPrerender: boolean;
20
+ }
File without changes
@@ -0,0 +1,7 @@
1
+ import type { NuxtModule } from '@nuxt/schema'
2
+
3
+ import type { default as Module } from './module.mjs'
4
+
5
+ export type ModuleOptions = typeof Module extends NuxtModule<infer O> ? Partial<O> : Record<string, any>
6
+
7
+ export { default } from './module.mjs'
package/package.json ADDED
@@ -0,0 +1,65 @@
1
+ {
2
+ "name": "@mdream/nuxt",
3
+ "type": "module",
4
+ "version": "0.8.0",
5
+ "description": "Nuxt module for converting HTML pages to Markdown using mdream",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/types.d.mts",
10
+ "import": "./dist/module.mjs"
11
+ }
12
+ },
13
+ "main": "./dist/module.mjs",
14
+ "types": "./dist/types.d.mts",
15
+ "typesVersions": {
16
+ "*": {
17
+ ".": [
18
+ "./dist/types.d.mts"
19
+ ]
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "peerDependencies": {
26
+ "nuxt": "^3.0.0"
27
+ },
28
+ "dependencies": {
29
+ "@nuxt/kit": "^3.17.6",
30
+ "consola": "^3.4.2",
31
+ "defu": "^6.1.4",
32
+ "nuxt-site-config": "^3.2.2",
33
+ "pathe": "^2.0.3",
34
+ "mdream": "0.8.0"
35
+ },
36
+ "devDependencies": {
37
+ "@antfu/eslint-config": "^4.16.2",
38
+ "@arethetypeswrong/cli": "^0.18.2",
39
+ "@nuxt/devtools": "latest",
40
+ "@nuxt/module-builder": "^1.0.1",
41
+ "@nuxt/schema": "^3.17.6",
42
+ "@nuxt/test-utils": "^3.19.2",
43
+ "@types/node": "latest",
44
+ "bumpp": "^10.2.0",
45
+ "changelogen": "^0.6.2",
46
+ "eslint": "^9.30.1",
47
+ "nuxt": "^3.17.6",
48
+ "typescript": "^5.8.3",
49
+ "vitest": "^3.2.4"
50
+ },
51
+ "scripts": {
52
+ "build": "pnpm run dev:prepare && nuxt-module-build build",
53
+ "dev": "nuxi dev playground",
54
+ "dev:build": "nuxi build playground",
55
+ "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
56
+ "prepare:fixtures": "nuxi prepare test/fixtures/basic",
57
+ "release": "pnpm build && bumpp && pnpm -r publish",
58
+ "test": "pnpm prepare:fixtures && vitest run",
59
+ "test:watch": "vitest watch",
60
+ "test:attw": "attw --pack",
61
+ "typecheck": "tsc --noEmit",
62
+ "lint": "eslint .",
63
+ "lint:fix": "eslint . --fix"
64
+ }
65
+ }