fumadocs-mdx 8.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Fuma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,58 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
+ var __spreadValues = (a, b) => {
9
+ for (var prop in b || (b = {}))
10
+ if (__hasOwnProp.call(b, prop))
11
+ __defNormalProp(a, prop, b[prop]);
12
+ if (__getOwnPropSymbols)
13
+ for (var prop of __getOwnPropSymbols(b)) {
14
+ if (__propIsEnum.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ }
17
+ return a;
18
+ };
19
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ var __objRest = (source, exclude) => {
21
+ var target = {};
22
+ for (var prop in source)
23
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
24
+ target[prop] = source[prop];
25
+ if (source != null && __getOwnPropSymbols)
26
+ for (var prop of __getOwnPropSymbols(source)) {
27
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
28
+ target[prop] = source[prop];
29
+ }
30
+ return target;
31
+ };
32
+ var __async = (__this, __arguments, generator) => {
33
+ return new Promise((resolve, reject) => {
34
+ var fulfilled = (value) => {
35
+ try {
36
+ step(generator.next(value));
37
+ } catch (e) {
38
+ reject(e);
39
+ }
40
+ };
41
+ var rejected = (value) => {
42
+ try {
43
+ step(generator.throw(value));
44
+ } catch (e) {
45
+ reject(e);
46
+ }
47
+ };
48
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
49
+ step((generator = generator.apply(__this, __arguments)).next());
50
+ });
51
+ };
52
+
53
+ export {
54
+ __spreadValues,
55
+ __spreadProps,
56
+ __objRest,
57
+ __async
58
+ };
@@ -0,0 +1,138 @@
1
+ import * as next_dist_shared_lib_image_config from 'next/dist/shared/lib/image-config';
2
+ import * as next_dist_lib_load_custom_routes from 'next/dist/lib/load-custom-routes';
3
+ import * as next_dist_server_config_shared from 'next/dist/server/config-shared';
4
+ import { NextConfig } from 'next';
5
+ import { RemarkImageOptions, RehypeCodeOptions } from 'fumadocs-core/mdx-plugins';
6
+ import { PluggableList } from 'unified';
7
+ import { Configuration } from 'webpack';
8
+ import { Options } from './loader-mdx.mjs';
9
+ import '@mdx-js/mdx';
10
+
11
+ type MDXOptions = Omit<NonNullable<Options>, 'rehypePlugins' | 'remarkPlugins'> & {
12
+ rehypePlugins?: ResolvePlugins;
13
+ remarkPlugins?: ResolvePlugins;
14
+ /**
15
+ * Properties to export from `vfile.data`
16
+ */
17
+ valueToExport?: string[];
18
+ remarkImageOptions?: RemarkImageOptions;
19
+ rehypeCodeOptions?: RehypeCodeOptions;
20
+ };
21
+ type ResolvePlugins = PluggableList | ((v: PluggableList) => PluggableList);
22
+ interface NextDocsMDXOptions {
23
+ cwd?: string;
24
+ mdxOptions?: MDXOptions;
25
+ /**
26
+ * Where the root map.ts should be, relative to cwd
27
+ *
28
+ * @defaultValue `'./.map.ts'`
29
+ */
30
+ rootMapPath?: string;
31
+ /**
32
+ * Where the content directory should be, relative to cwd
33
+ *
34
+ * @defaultValue `'./content'`
35
+ */
36
+ rootContentPath?: string;
37
+ }
38
+ declare const createNextDocs: ({ mdxOptions, cwd, rootMapPath, rootContentPath, }?: NextDocsMDXOptions) => (nextConfig?: NextConfig) => {
39
+ webpack: (config: Configuration, options: next_dist_server_config_shared.WebpackConfigContext) => any;
40
+ exportPathMap?: ((defaultMap: next_dist_server_config_shared.ExportPathMap, ctx: {
41
+ dev: boolean;
42
+ dir: string;
43
+ outDir: string | null;
44
+ distDir: string;
45
+ buildId: string;
46
+ }) => next_dist_server_config_shared.ExportPathMap | Promise<next_dist_server_config_shared.ExportPathMap>) | undefined;
47
+ i18n?: next_dist_server_config_shared.I18NConfig | null | undefined;
48
+ eslint?: next_dist_server_config_shared.ESLintConfig | undefined;
49
+ typescript?: next_dist_server_config_shared.TypeScriptConfig | undefined;
50
+ headers?: (() => Promise<next_dist_lib_load_custom_routes.Header[]>) | undefined;
51
+ rewrites?: (() => Promise<next_dist_lib_load_custom_routes.Rewrite[] | {
52
+ beforeFiles: next_dist_lib_load_custom_routes.Rewrite[];
53
+ afterFiles: next_dist_lib_load_custom_routes.Rewrite[];
54
+ fallback: next_dist_lib_load_custom_routes.Rewrite[];
55
+ }>) | undefined;
56
+ redirects?: (() => Promise<next_dist_lib_load_custom_routes.Redirect[]>) | undefined;
57
+ excludeDefaultMomentLocales?: boolean | undefined;
58
+ trailingSlash?: boolean | undefined;
59
+ env?: Record<string, string | undefined> | undefined;
60
+ distDir?: string | undefined;
61
+ cleanDistDir?: boolean | undefined;
62
+ assetPrefix?: string | undefined;
63
+ cacheHandler?: string | undefined;
64
+ cacheMaxMemorySize?: number | undefined;
65
+ useFileSystemPublicRoutes?: boolean | undefined;
66
+ generateBuildId?: (() => string | Promise<string | null> | null) | undefined;
67
+ generateEtags?: boolean | undefined;
68
+ pageExtensions?: string[] | undefined;
69
+ compress?: boolean | undefined;
70
+ analyticsId?: string | undefined;
71
+ poweredByHeader?: boolean | undefined;
72
+ images?: Partial<next_dist_shared_lib_image_config.ImageConfigComplete> | undefined;
73
+ devIndicators?: {
74
+ buildActivity?: boolean | undefined;
75
+ buildActivityPosition?: "bottom-right" | "bottom-left" | "top-right" | "top-left" | undefined;
76
+ } | undefined;
77
+ onDemandEntries?: {
78
+ maxInactiveAge?: number | undefined;
79
+ pagesBufferLength?: number | undefined;
80
+ } | undefined;
81
+ amp?: {
82
+ canonicalBase?: string | undefined;
83
+ } | undefined;
84
+ basePath?: string | undefined;
85
+ sassOptions?: {
86
+ [key: string]: any;
87
+ } | undefined;
88
+ productionBrowserSourceMaps?: boolean | undefined;
89
+ optimizeFonts?: boolean | undefined;
90
+ reactProductionProfiling?: boolean | undefined;
91
+ reactStrictMode?: boolean | null | undefined;
92
+ publicRuntimeConfig?: {
93
+ [key: string]: any;
94
+ } | undefined;
95
+ serverRuntimeConfig?: {
96
+ [key: string]: any;
97
+ } | undefined;
98
+ httpAgentOptions?: {
99
+ keepAlive?: boolean | undefined;
100
+ } | undefined;
101
+ outputFileTracing?: boolean | undefined;
102
+ staticPageGenerationTimeout?: number | undefined;
103
+ crossOrigin?: false | "anonymous" | "use-credentials" | undefined;
104
+ swcMinify?: boolean | undefined;
105
+ compiler?: {
106
+ reactRemoveProperties?: boolean | {
107
+ properties?: string[] | undefined;
108
+ } | undefined;
109
+ relay?: {
110
+ src: string;
111
+ artifactDirectory?: string | undefined;
112
+ language?: "typescript" | "javascript" | "flow" | undefined;
113
+ eagerEsModules?: boolean | undefined;
114
+ } | undefined;
115
+ removeConsole?: boolean | {
116
+ exclude?: string[] | undefined;
117
+ } | undefined;
118
+ styledComponents?: boolean | next_dist_server_config_shared.StyledComponentsConfig | undefined;
119
+ emotion?: boolean | next_dist_server_config_shared.EmotionConfig | undefined;
120
+ } | undefined;
121
+ output?: "standalone" | "export" | undefined;
122
+ transpilePackages?: string[] | undefined;
123
+ skipMiddlewareUrlNormalize?: boolean | undefined;
124
+ skipTrailingSlashRedirect?: boolean | undefined;
125
+ modularizeImports?: Record<string, {
126
+ transform: string | Record<string, string>;
127
+ preventFullImport?: boolean | undefined;
128
+ skipDefaultConversion?: boolean | undefined;
129
+ }> | undefined;
130
+ logging?: {
131
+ fetches?: {
132
+ fullUrl?: boolean | undefined;
133
+ } | undefined;
134
+ } | undefined;
135
+ experimental?: next_dist_server_config_shared.ExperimentalConfig | undefined;
136
+ };
137
+
138
+ export { createNextDocs as default };
@@ -0,0 +1,176 @@
1
+ import {
2
+ __spreadProps,
3
+ __spreadValues
4
+ } from "./chunk-P26LYDRL.mjs";
5
+
6
+ // src/config.ts
7
+ import path from "path";
8
+ import {
9
+ rehypeCode,
10
+ remarkGfm,
11
+ remarkStructure,
12
+ remarkHeading,
13
+ remarkImage
14
+ } from "fumadocs-core/mdx-plugins";
15
+
16
+ // src/webpack-plugins/next-docs.ts
17
+ import fs from "fs";
18
+ var firstLoad = true;
19
+ var content = `
20
+ /** Auto-generated **/
21
+ declare const map: Record<string, unknown>
22
+
23
+ export { map }
24
+ `.trim();
25
+ var NextDocsWebpackPlugin = class _NextDocsWebpackPlugin {
26
+ constructor(options) {
27
+ this.options = options;
28
+ }
29
+ apply(compiler) {
30
+ const logger = compiler.getInfrastructureLogger(_NextDocsWebpackPlugin.name);
31
+ compiler.hooks.beforeCompile.tap(_NextDocsWebpackPlugin.name, () => {
32
+ if (firstLoad && !fs.existsSync(this.options.rootMapFile)) {
33
+ fs.writeFileSync(this.options.rootMapFile, content);
34
+ logger.info("Created map.ts file for you automatically");
35
+ firstLoad = false;
36
+ }
37
+ });
38
+ }
39
+ };
40
+
41
+ // src/mdx-plugins/utils.ts
42
+ import { valueToEstree } from "estree-util-value-to-estree";
43
+ function getMdastExport(name, value) {
44
+ return {
45
+ type: "mdxjsEsm",
46
+ value: "",
47
+ data: {
48
+ estree: {
49
+ type: "Program",
50
+ sourceType: "module",
51
+ body: [
52
+ {
53
+ type: "ExportNamedDeclaration",
54
+ specifiers: [],
55
+ source: null,
56
+ declaration: {
57
+ type: "VariableDeclaration",
58
+ kind: "const",
59
+ declarations: [
60
+ {
61
+ type: "VariableDeclarator",
62
+ id: {
63
+ type: "Identifier",
64
+ name
65
+ },
66
+ init: valueToEstree(value)
67
+ }
68
+ ]
69
+ }
70
+ }
71
+ ]
72
+ }
73
+ }
74
+ };
75
+ }
76
+
77
+ // src/mdx-plugins/remark-exports.ts
78
+ function remarkMdxExport({ values }) {
79
+ return (tree, vfile) => {
80
+ for (const name of values) {
81
+ if (!(name in vfile.data))
82
+ return;
83
+ tree.children.unshift(getMdastExport(name, vfile.data[name]));
84
+ }
85
+ };
86
+ }
87
+
88
+ // src/config.ts
89
+ function pluginOption(def, options = []) {
90
+ const list = def(Array.isArray(options) ? options : []);
91
+ if (typeof options === "function") {
92
+ return options(list);
93
+ }
94
+ return list;
95
+ }
96
+ var createNextDocs = ({
97
+ mdxOptions = {},
98
+ cwd = process.cwd(),
99
+ rootMapPath = "./.map.ts",
100
+ rootContentPath = "./content"
101
+ } = {}) => (nextConfig = {}) => {
102
+ var _a;
103
+ const valueToExport = [
104
+ "structuredData",
105
+ "toc",
106
+ "frontmatter",
107
+ "lastModified",
108
+ ...(_a = mdxOptions.valueToExport) != null ? _a : []
109
+ ];
110
+ const _mapPath = path.resolve(cwd, rootMapPath);
111
+ const remarkPlugins = pluginOption(
112
+ (v) => [
113
+ remarkGfm,
114
+ remarkHeading,
115
+ [remarkImage, mdxOptions.remarkImageOptions],
116
+ ...v,
117
+ remarkStructure,
118
+ [remarkMdxExport, { values: valueToExport }]
119
+ ],
120
+ mdxOptions.remarkPlugins
121
+ );
122
+ const rehypePlugins = pluginOption(
123
+ (v) => [[rehypeCode, mdxOptions.rehypeCodeOptions], ...v],
124
+ mdxOptions.rehypePlugins
125
+ );
126
+ return __spreadValues(__spreadValues({}, nextConfig), {
127
+ webpack: (config, options) => {
128
+ var _a2, _b, _c;
129
+ config.resolve || (config.resolve = {});
130
+ const alias = config.resolve.alias;
131
+ alias["next-mdx-import-source-file"] = [
132
+ "private-next-root-dir/src/mdx-components",
133
+ "private-next-root-dir/mdx-components",
134
+ "@mdx-js/react"
135
+ ];
136
+ config.module || (config.module = {});
137
+ (_a2 = config.module).rules || (_a2.rules = []);
138
+ config.module.rules.push(
139
+ {
140
+ test: /\.mdx?$/,
141
+ use: [
142
+ options.defaultLoaders.babel,
143
+ {
144
+ loader: "fumadocs-mdx/loader-mdx",
145
+ options: __spreadProps(__spreadValues({
146
+ providerImportSource: "next-mdx-import-source-file"
147
+ }, mdxOptions), {
148
+ remarkPlugins,
149
+ rehypePlugins
150
+ })
151
+ }
152
+ ]
153
+ },
154
+ {
155
+ test: _mapPath,
156
+ use: {
157
+ loader: "fumadocs-mdx/loader",
158
+ options: {
159
+ cwd,
160
+ rootContentPath,
161
+ mapPath: _mapPath
162
+ }
163
+ }
164
+ }
165
+ );
166
+ config.plugins || (config.plugins = []);
167
+ config.plugins.push(
168
+ new NextDocsWebpackPlugin({ rootMapFile: _mapPath })
169
+ );
170
+ return (_c = (_b = nextConfig.webpack) == null ? void 0 : _b.call(nextConfig, config, options)) != null ? _c : config;
171
+ }
172
+ });
173
+ };
174
+ export {
175
+ createNextDocs as default
176
+ };
@@ -0,0 +1,79 @@
1
+ import { MetaData, PageData, Source } from 'fumadocs-core/source';
2
+ import { z } from 'zod';
3
+ import { MDXProps } from 'mdx/types';
4
+ import { StructuredData } from 'fumadocs-core/mdx-plugins';
5
+ import { TableOfContents } from 'fumadocs-core/server';
6
+
7
+ declare const defaultSchemas: {
8
+ frontmatter: z.ZodObject<{
9
+ title: z.ZodString;
10
+ description: z.ZodOptional<z.ZodString>;
11
+ icon: z.ZodOptional<z.ZodString>;
12
+ }, "strip", z.ZodTypeAny, {
13
+ title: string;
14
+ description?: string | undefined;
15
+ icon?: string | undefined;
16
+ }, {
17
+ title: string;
18
+ description?: string | undefined;
19
+ icon?: string | undefined;
20
+ }>;
21
+ meta: z.ZodObject<{
22
+ title: z.ZodOptional<z.ZodString>;
23
+ pages: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
24
+ root: z.ZodOptional<z.ZodBoolean>;
25
+ icon: z.ZodOptional<z.ZodString>;
26
+ }, "strip", z.ZodTypeAny, {
27
+ title?: string | undefined;
28
+ pages?: string[] | undefined;
29
+ root?: boolean | undefined;
30
+ icon?: string | undefined;
31
+ }, {
32
+ title?: string | undefined;
33
+ pages?: string[] | undefined;
34
+ root?: boolean | undefined;
35
+ icon?: string | undefined;
36
+ }>;
37
+ };
38
+
39
+ type SourceFile<Meta extends MetaData, Fronmatter extends PageData> = {
40
+ type: 'meta';
41
+ path: string;
42
+ data: Meta;
43
+ } | {
44
+ type: 'page';
45
+ path: string;
46
+ data: MDXPageData<Fronmatter>;
47
+ };
48
+ /**
49
+ * Defalt MDX properties
50
+ */
51
+ interface MDXExport<Frontmatter = PageData> {
52
+ default: (props: MDXProps) => JSX.Element;
53
+ frontmatter: Frontmatter;
54
+ lastModified: number | undefined;
55
+ toc: TableOfContents;
56
+ structuredData: StructuredData;
57
+ }
58
+ type MDXPageData<Frontmatter extends PageData = PageData> = Omit<Frontmatter, 'exports'> & {
59
+ exports: Omit<MDXExport<Frontmatter>, 'frontmatter'>;
60
+ };
61
+
62
+ interface SourceOptions<Frontmatter, Meta> {
63
+ schema?: {
64
+ frontmatter?: Frontmatter;
65
+ meta?: Meta;
66
+ };
67
+ }
68
+ interface LoadOptions<Frontmatter, Meta> extends SourceOptions<Frontmatter, Meta> {
69
+ rootDir?: string;
70
+ }
71
+ type DefaultFrontmatter = (typeof defaultSchemas)['frontmatter'];
72
+ type DefaultMeta = (typeof defaultSchemas)['meta'];
73
+ declare function createMDXSource<Frontmatter extends DefaultFrontmatter = DefaultFrontmatter, Meta extends DefaultMeta = DefaultMeta>(map: Record<string, unknown>, options?: SourceOptions<Frontmatter, Meta>): Source<{
74
+ metaData: z.infer<Meta>;
75
+ pageData: MDXPageData<z.infer<Frontmatter>>;
76
+ }>;
77
+ declare function loadMDXSource<Frontmatter extends DefaultFrontmatter = DefaultFrontmatter, Meta extends DefaultMeta = DefaultMeta>(map: Record<string, unknown>, options?: LoadOptions<Frontmatter, Meta>): SourceFile<z.infer<Meta>, z.infer<Frontmatter>>[];
78
+
79
+ export { type MDXExport, type MDXPageData, type SourceFile, createMDXSource, defaultSchemas, loadMDXSource };
package/dist/index.mjs ADDED
@@ -0,0 +1,93 @@
1
+ import {
2
+ __objRest,
3
+ __spreadProps,
4
+ __spreadValues
5
+ } from "./chunk-P26LYDRL.mjs";
6
+
7
+ // src/resolve-files.ts
8
+ import path from "path";
9
+
10
+ // src/utils/schema.ts
11
+ import { z } from "zod";
12
+ var metaSchema = z.object({
13
+ title: z.string().optional(),
14
+ pages: z.array(z.string()).optional(),
15
+ root: z.boolean().optional(),
16
+ icon: z.string().optional()
17
+ });
18
+ var frontmatterSchema = z.object({
19
+ title: z.string(),
20
+ description: z.string().optional(),
21
+ icon: z.string().optional()
22
+ });
23
+ var defaultSchemas = {
24
+ frontmatter: frontmatterSchema,
25
+ meta: metaSchema
26
+ };
27
+
28
+ // src/resolve-files.ts
29
+ var pageTypes = [".md", ".mdx"];
30
+ var metaTypes = [".json"];
31
+ function parse(schema, object, errorName) {
32
+ const result = schema.safeParse(object);
33
+ if (!result.success) {
34
+ throw new Error(`Invalid ${errorName}: ${result.error.toString()}`);
35
+ }
36
+ return result.data;
37
+ }
38
+ function resolveFiles({
39
+ map,
40
+ rootDir = "",
41
+ schema = {}
42
+ }) {
43
+ var _a, _c;
44
+ const outputs = [];
45
+ for (const [file, value] of Object.entries(map)) {
46
+ if (!file.startsWith(rootDir))
47
+ continue;
48
+ const parsed = path.parse(file);
49
+ if (metaTypes.includes(parsed.ext)) {
50
+ outputs.push({
51
+ type: "meta",
52
+ path: file,
53
+ data: parse((_a = schema.meta) != null ? _a : defaultSchemas.meta, value, file)
54
+ });
55
+ continue;
56
+ }
57
+ if (pageTypes.includes(parsed.ext)) {
58
+ const _b = value, { frontmatter } = _b, data = __objRest(_b, ["frontmatter"]);
59
+ const parsedFrontmatter = parse(
60
+ (_c = schema.frontmatter) != null ? _c : defaultSchemas.frontmatter,
61
+ frontmatter,
62
+ file
63
+ );
64
+ outputs.push({
65
+ type: "page",
66
+ path: file,
67
+ data: __spreadProps(__spreadValues({}, parsedFrontmatter), {
68
+ exports: data
69
+ })
70
+ });
71
+ continue;
72
+ }
73
+ console.warn("Unknown Type:", parsed.ext);
74
+ }
75
+ return outputs;
76
+ }
77
+
78
+ // src/create.ts
79
+ function createMDXSource(map, options) {
80
+ return {
81
+ files: (rootDir) => loadMDXSource(map, __spreadProps(__spreadValues({}, options), { rootDir }))
82
+ };
83
+ }
84
+ function loadMDXSource(map, options) {
85
+ return resolveFiles(__spreadValues({
86
+ map
87
+ }, options));
88
+ }
89
+ export {
90
+ createMDXSource,
91
+ defaultSchemas,
92
+ loadMDXSource
93
+ };
@@ -0,0 +1,27 @@
1
+ import { ProcessorOptions } from '@mdx-js/mdx';
2
+ import { LoaderContext } from 'webpack';
3
+
4
+ interface Options extends ProcessorOptions {
5
+ /**
6
+ * Fetch last modified time with specified version control
7
+ * @defaultValue 'none'
8
+ */
9
+ lastModifiedTime?: 'git' | 'none';
10
+ }
11
+ interface NextDocsBuildInfo {
12
+ __next_docs?: {
13
+ path: string;
14
+ /**
15
+ * `vfile.data` parsed from file
16
+ */
17
+ data: unknown;
18
+ };
19
+ }
20
+ /**
21
+ * Load MDX/markdown files
22
+ *
23
+ * it supports frontmatter by parsing and injecting the data in `vfile.data.frontmatter`
24
+ */
25
+ declare function loader(this: LoaderContext<Options>, source: string, callback: LoaderContext<Options>['callback']): Promise<void>;
26
+
27
+ export { type NextDocsBuildInfo, type Options, loader as default };
@@ -0,0 +1,93 @@
1
+ import {
2
+ __async,
3
+ __objRest,
4
+ __spreadProps,
5
+ __spreadValues
6
+ } from "./chunk-P26LYDRL.mjs";
7
+
8
+ // src/loader-mdx.ts
9
+ import path2 from "path";
10
+ import { createProcessor } from "@mdx-js/mdx";
11
+ import grayMatter from "gray-matter";
12
+
13
+ // src/utils/git-timestamp.ts
14
+ import path from "path";
15
+ import fs from "fs";
16
+ import { spawn } from "cross-spawn";
17
+ var cache = /* @__PURE__ */ new Map();
18
+ function getGitTimestamp(file) {
19
+ const cachedTimestamp = cache.get(file);
20
+ if (cachedTimestamp)
21
+ return Promise.resolve(cachedTimestamp);
22
+ return new Promise((resolve, reject) => {
23
+ const cwd = path.dirname(file);
24
+ if (!fs.existsSync(cwd)) {
25
+ resolve(void 0);
26
+ return;
27
+ }
28
+ const fileName = path.basename(file);
29
+ const child = spawn("git", ["log", "-1", '--pretty="%ai"', fileName], {
30
+ cwd
31
+ });
32
+ let output;
33
+ child.stdout.on("data", (d) => output = new Date(String(d)));
34
+ child.on("close", () => {
35
+ if (output)
36
+ cache.set(file, output);
37
+ resolve(output);
38
+ });
39
+ child.on("error", reject);
40
+ });
41
+ }
42
+
43
+ // src/loader-mdx.ts
44
+ var cache2 = /* @__PURE__ */ new Map();
45
+ function loader(source, callback) {
46
+ return __async(this, null, function* () {
47
+ var _b, _c;
48
+ this.cacheable(true);
49
+ const context = this.context;
50
+ const filePath = this.resourcePath;
51
+ const _a = this.getOptions(), { lastModifiedTime } = _a, options = __objRest(_a, ["lastModifiedTime"]);
52
+ const { content, data: frontmatter } = grayMatter(source);
53
+ const detectedFormat = filePath.endsWith(".mdx") ? "mdx" : "md";
54
+ const format = (_b = options.format) != null ? _b : detectedFormat;
55
+ let timestamp;
56
+ let processor = cache2.get(format);
57
+ if (processor === void 0) {
58
+ processor = createProcessor(__spreadProps(__spreadValues({}, options), {
59
+ development: this.mode === "development",
60
+ format
61
+ }));
62
+ cache2.set(format, processor);
63
+ }
64
+ if (lastModifiedTime === "git")
65
+ timestamp = (_c = yield getGitTimestamp(filePath)) == null ? void 0 : _c.getTime();
66
+ processor.process({
67
+ value: content,
68
+ path: filePath,
69
+ data: {
70
+ lastModified: timestamp,
71
+ frontmatter
72
+ }
73
+ }).then(
74
+ (file) => {
75
+ var _a2;
76
+ const info = (_a2 = this._module) == null ? void 0 : _a2.buildInfo;
77
+ info.__next_docs = {
78
+ path: filePath,
79
+ data: file.data
80
+ };
81
+ callback(void 0, String(file.value), file.map || void 0);
82
+ },
83
+ (error) => {
84
+ const fpath = path2.relative(context, filePath);
85
+ error.message = `${fpath}:${error.name}: ${error.message}`;
86
+ callback(error);
87
+ }
88
+ );
89
+ });
90
+ }
91
+ export {
92
+ loader as default
93
+ };
@@ -0,0 +1,13 @@
1
+ import { LoaderContext } from 'webpack';
2
+
3
+ interface LoaderOptions {
4
+ rootContentPath: string;
5
+ mapPath: string;
6
+ cwd: string;
7
+ }
8
+ /**
9
+ * Load the root `.map.ts` file
10
+ */
11
+ declare function loader(this: LoaderContext<LoaderOptions>, _source: string, callback: LoaderContext<LoaderOptions>['callback']): void;
12
+
13
+ export { type LoaderOptions, loader as default };
@@ -0,0 +1,31 @@
1
+ import "./chunk-P26LYDRL.mjs";
2
+
3
+ // src/loader.ts
4
+ import path from "path";
5
+ import fg from "fast-glob";
6
+ function loader(_source, callback) {
7
+ const options = this.getOptions();
8
+ this.cacheable(true);
9
+ this.addContextDependency(path.resolve(options.cwd, options.rootContentPath));
10
+ callback(null, buildMap(options));
11
+ }
12
+ function buildMap({ cwd, rootContentPath, mapPath }) {
13
+ const mapDir = path.dirname(mapPath);
14
+ const absoluteContentPath = path.resolve(cwd, rootContentPath);
15
+ const files = fg.sync("./**/*.{md,mdx,json}", {
16
+ cwd: absoluteContentPath
17
+ });
18
+ const entries = files.map((file) => {
19
+ let importPath = path.relative(mapDir, path.join(absoluteContentPath, file)).replace(path.sep, "/");
20
+ if (!importPath.startsWith(".")) {
21
+ importPath = `./${importPath}`;
22
+ }
23
+ return `${JSON.stringify(file)}: await import(${JSON.stringify(
24
+ importPath
25
+ )})`;
26
+ });
27
+ return `export const map = {${entries.join(",")}}`;
28
+ }
29
+ export {
30
+ loader as default
31
+ };
package/loader-mdx.js ADDED
@@ -0,0 +1,8 @@
1
+ /* eslint-env node -- Node.js env */
2
+
3
+ module.exports = function loader(code) {
4
+ const callback = this.async();
5
+ import('./dist/loader-mdx.mjs').then((mod) =>
6
+ mod.default.call(this, code, callback),
7
+ );
8
+ };
package/loader.js ADDED
@@ -0,0 +1,8 @@
1
+ /* eslint-env node -- Node.js env */
2
+
3
+ module.exports = function loader(code) {
4
+ const callback = this.async();
5
+ import('./dist/loader.mjs').then((mod) =>
6
+ mod.default.call(this, code, callback),
7
+ );
8
+ };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "fumadocs-mdx",
3
+ "version": "8.0.0",
4
+ "description": "The built-in source for Fumadocs",
5
+ "keywords": [
6
+ "NextJs",
7
+ "Docs"
8
+ ],
9
+ "homepage": "https://fumadocs.vercel.app",
10
+ "repository": "github:fuma-nama/next-docs",
11
+ "license": "MIT",
12
+ "author": "Fuma Nama",
13
+ "exports": {
14
+ "./loader": "./loader.js",
15
+ "./loader-mdx": "./loader-mdx.js",
16
+ "./config": {
17
+ "import": "./dist/config.mjs",
18
+ "types": "./dist/config.d.mts"
19
+ },
20
+ ".": {
21
+ "import": "./dist/index.mjs",
22
+ "types": "./dist/index.mts"
23
+ }
24
+ },
25
+ "main": "./dist/index.mjs",
26
+ "types": "./dist/index.mts",
27
+ "typesVersions": {
28
+ "*": {
29
+ "config": [
30
+ "./dist/config.d.mts"
31
+ ]
32
+ }
33
+ },
34
+ "files": [
35
+ "dist/*",
36
+ "loader-mdx.js",
37
+ "loader.js"
38
+ ],
39
+ "dependencies": {
40
+ "@mdx-js/mdx": "^3.0.0",
41
+ "cross-spawn": "^7.0.3",
42
+ "estree-util-value-to-estree": "^3.0.1",
43
+ "fast-glob": "^3.3.1",
44
+ "gray-matter": "^4.0.3",
45
+ "zod": "^3.22.4",
46
+ "fumadocs-core": "8.0.0"
47
+ },
48
+ "devDependencies": {
49
+ "@types/cross-spawn": "^6.0.4",
50
+ "@types/mdast": "^4.0.3",
51
+ "@types/mdx": "^2.0.8",
52
+ "@types/react": "18.2.0",
53
+ "next": "14.1.0",
54
+ "unified": "^11.0.4",
55
+ "webpack": "^5.89.0",
56
+ "eslint-config-custom": "0.0.0",
57
+ "tsconfig": "0.0.0"
58
+ },
59
+ "peerDependencies": {
60
+ "next": ">= 13.4"
61
+ },
62
+ "publishConfig": {
63
+ "access": "public"
64
+ },
65
+ "scripts": {
66
+ "build": "tsup",
67
+ "clean": "rimraf dist",
68
+ "dev": "tsup --watch",
69
+ "lint": "eslint .",
70
+ "types:check": "tsc --noEmit"
71
+ }
72
+ }