fumadocs-mdx 14.2.3 → 14.2.4

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.
Files changed (116) hide show
  1. package/dist/adapter-DG-viEbG.js +144 -0
  2. package/dist/adapter-DG-viEbG.js.map +1 -0
  3. package/dist/bin.d.ts +1 -1
  4. package/dist/bin.js +21 -12
  5. package/dist/bin.js.map +1 -0
  6. package/dist/build-BTTNEFmV.js +100 -0
  7. package/dist/build-BTTNEFmV.js.map +1 -0
  8. package/dist/build-mdx-10MrLupc.d.ts +53 -0
  9. package/dist/build-mdx-10MrLupc.d.ts.map +1 -0
  10. package/dist/build-mdx-BVeBo4jT.js +153 -0
  11. package/dist/build-mdx-BVeBo4jT.js.map +1 -0
  12. package/dist/build-mdx-ChjP7zAn.js +5 -0
  13. package/dist/bun/index.d.ts +10 -21
  14. package/dist/bun/index.d.ts.map +1 -0
  15. package/dist/bun/index.js +30 -49
  16. package/dist/bun/index.js.map +1 -0
  17. package/dist/codegen-DleOVLNr.js +101 -0
  18. package/dist/codegen-DleOVLNr.js.map +1 -0
  19. package/dist/config/index.d.ts +2 -18
  20. package/dist/config/index.js +50 -53
  21. package/dist/config/index.js.map +1 -0
  22. package/dist/core-DG43f_AU.d.ts +364 -0
  23. package/dist/core-DG43f_AU.d.ts.map +1 -0
  24. package/dist/core-DjldE3H9.js +212 -0
  25. package/dist/core-DjldE3H9.js.map +1 -0
  26. package/dist/fuma-matter-CHgJa_-B.js +27 -0
  27. package/dist/fuma-matter-CHgJa_-B.js.map +1 -0
  28. package/dist/index-Bc_4I1HE.d.ts +12 -0
  29. package/dist/index-Bc_4I1HE.d.ts.map +1 -0
  30. package/dist/index-file-D9HsrWU_.js +264 -0
  31. package/dist/index-file-D9HsrWU_.js.map +1 -0
  32. package/dist/index.d.ts +3 -61
  33. package/dist/index.js +1 -0
  34. package/dist/load-from-file-B7Rswy9i.js +5 -0
  35. package/dist/load-from-file-Doc98oEB.js +38 -0
  36. package/dist/load-from-file-Doc98oEB.js.map +1 -0
  37. package/dist/loaders-BVwYfelL.js +7 -0
  38. package/dist/loaders-BVwYfelL.js.map +1 -0
  39. package/dist/mdx-DMZ9tsAa.js +91 -0
  40. package/dist/mdx-DMZ9tsAa.js.map +1 -0
  41. package/dist/meta-DyieTM4Z.js +81 -0
  42. package/dist/meta-DyieTM4Z.js.map +1 -0
  43. package/dist/next/index.cjs +863 -1076
  44. package/dist/next/index.d.ts +17 -28
  45. package/dist/next/index.d.ts.map +1 -0
  46. package/dist/next/index.js +141 -170
  47. package/dist/next/index.js.map +1 -0
  48. package/dist/node/loader.d.ts +4 -2
  49. package/dist/node/loader.d.ts.map +1 -0
  50. package/dist/node/loader.js +26 -38
  51. package/dist/node/loader.js.map +1 -0
  52. package/dist/plugins/index-file.d.ts +2 -14
  53. package/dist/plugins/index-file.js +5 -8
  54. package/dist/plugins/json-schema.d.ts +14 -23
  55. package/dist/plugins/json-schema.d.ts.map +1 -0
  56. package/dist/plugins/json-schema.js +70 -78
  57. package/dist/plugins/json-schema.js.map +1 -0
  58. package/dist/plugins/last-modified.d.ts +21 -32
  59. package/dist/plugins/last-modified.d.ts.map +1 -0
  60. package/dist/plugins/last-modified.js +70 -78
  61. package/dist/plugins/last-modified.js.map +1 -0
  62. package/dist/preset-gmDZnBcg.js +61 -0
  63. package/dist/preset-gmDZnBcg.js.map +1 -0
  64. package/dist/remark-include-D3G3mAnv.js +247 -0
  65. package/dist/remark-include-D3G3mAnv.js.map +1 -0
  66. package/dist/runtime/browser.d.ts +32 -41
  67. package/dist/runtime/browser.d.ts.map +1 -0
  68. package/dist/runtime/browser.js +56 -63
  69. package/dist/runtime/browser.js.map +1 -0
  70. package/dist/runtime/dynamic.d.ts +13 -21
  71. package/dist/runtime/dynamic.d.ts.map +1 -0
  72. package/dist/runtime/dynamic.js +64 -76
  73. package/dist/runtime/dynamic.js.map +1 -0
  74. package/dist/runtime/server.d.ts +2 -14
  75. package/dist/runtime/server.js +111 -8
  76. package/dist/runtime/server.js.map +1 -0
  77. package/dist/runtime/types.d.ts +2 -61
  78. package/dist/runtime/types.js +1 -0
  79. package/dist/types-B6myALSk.d.ts +63 -0
  80. package/dist/types-B6myALSk.d.ts.map +1 -0
  81. package/dist/vite/index.d.ts +28 -39
  82. package/dist/vite/index.d.ts.map +1 -0
  83. package/dist/vite/index.js +79 -122
  84. package/dist/vite/index.js.map +1 -0
  85. package/dist/webpack/mdx.d.ts +6 -3
  86. package/dist/webpack/mdx.d.ts.map +1 -0
  87. package/dist/webpack/mdx.js +21 -34
  88. package/dist/webpack/mdx.js.map +1 -0
  89. package/dist/webpack/meta.d.ts +6 -3
  90. package/dist/webpack/meta.d.ts.map +1 -0
  91. package/dist/webpack/meta.js +23 -37
  92. package/dist/webpack/meta.js.map +1 -0
  93. package/dist/webpack--VSEE6Zp.js +15 -0
  94. package/dist/webpack--VSEE6Zp.js.map +1 -0
  95. package/loader-mdx.cjs +1 -3
  96. package/loader-meta.cjs +1 -3
  97. package/package.json +35 -35
  98. package/dist/build-mdx-5XLFMP5P.js +0 -8
  99. package/dist/chunk-257RZJEQ.js +0 -17
  100. package/dist/chunk-2PY3JUIC.js +0 -126
  101. package/dist/chunk-4EUH5CD2.js +0 -173
  102. package/dist/chunk-4JSFLXXT.js +0 -8
  103. package/dist/chunk-5OBUOALK.js +0 -141
  104. package/dist/chunk-DTFUANSF.js +0 -40
  105. package/dist/chunk-KWSETXYC.js +0 -274
  106. package/dist/chunk-OLD35ARB.js +0 -116
  107. package/dist/chunk-RSASAHLX.js +0 -91
  108. package/dist/chunk-S7KOJHHO.js +0 -89
  109. package/dist/chunk-STLEUNK7.js +0 -335
  110. package/dist/chunk-USQZ5OLE.js +0 -116
  111. package/dist/chunk-VWJKRQZR.js +0 -19
  112. package/dist/chunk-WFDF56IJ.js +0 -290
  113. package/dist/chunk-XYVVDDIF.js +0 -180
  114. package/dist/core-X5ggQtBM.d.ts +0 -350
  115. package/dist/index-BqkSNsGO.d.ts +0 -8
  116. package/dist/load-from-file-FHW724YY.js +0 -8
@@ -1,1165 +1,952 @@
1
- "use strict";
1
+ //#region rolldown:runtime
2
2
  var __create = Object.create;
3
3
  var __defProp = Object.defineProperty;
4
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
8
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
19
21
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/next/index.ts
31
- var next_exports = {};
32
- __export(next_exports, {
33
- createMDX: () => createMDX,
34
- postInstall: () => postInstall
35
- });
36
- module.exports = __toCommonJS(next_exports);
37
- var path6 = __toESM(require("path"), 1);
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
38
26
 
39
- // src/config/load-from-file.ts
40
- var import_node_url = require("url");
27
+ //#endregion
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path);
30
+ let node_url = require("node:url");
31
+ let picomatch = require("picomatch");
32
+ picomatch = __toESM(picomatch);
33
+ let node_fs_promises = require("node:fs/promises");
34
+ node_fs_promises = __toESM(node_fs_promises);
35
+ let tinyglobby = require("tinyglobby");
36
+ let path = require("path");
37
+ path = __toESM(path);
38
+ let crypto = require("crypto");
39
+ let js_yaml = require("js-yaml");
41
40
 
42
- // src/config/build.ts
43
- var import_picomatch = __toESM(require("picomatch"), 1);
44
-
45
- // src/config/preset.ts
41
+ //#region src/config/preset.ts
46
42
  function pluginOption(def, options = []) {
47
- const list = def(Array.isArray(options) ? options : []).filter(
48
- Boolean
49
- );
50
- if (typeof options === "function") {
51
- return options(list);
52
- }
53
- return list;
43
+ const list = def(Array.isArray(options) ? options : []).filter(Boolean);
44
+ if (typeof options === "function") return options(list);
45
+ return list;
54
46
  }
47
+ /**
48
+ * apply MDX processor presets
49
+ */
55
50
  function applyMdxPreset(options = {}) {
56
- return async (environment = "bundler") => {
57
- if (options.preset === "minimal") return options;
58
- const plugins = await import("fumadocs-core/mdx-plugins");
59
- const {
60
- valueToExport = [],
61
- rehypeCodeOptions,
62
- remarkImageOptions,
63
- remarkHeadingOptions,
64
- remarkStructureOptions,
65
- remarkCodeTabOptions,
66
- remarkNpmOptions,
67
- ...mdxOptions
68
- } = options;
69
- const remarkPlugins = pluginOption(
70
- (v) => [
71
- plugins.remarkGfm,
72
- [
73
- plugins.remarkHeading,
74
- {
75
- generateToc: false,
76
- ...remarkHeadingOptions
77
- }
78
- ],
79
- remarkImageOptions !== false && [
80
- plugins.remarkImage,
81
- {
82
- ...remarkImageOptions,
83
- useImport: remarkImageOptions?.useImport ?? environment === "bundler"
84
- }
85
- ],
86
- "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
87
- plugins.remarkCodeTab,
88
- remarkCodeTabOptions
89
- ],
90
- "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
91
- ...v,
92
- remarkStructureOptions !== false && [
93
- plugins.remarkStructure,
94
- {
95
- exportAs: "structuredData",
96
- ...remarkStructureOptions
97
- }
98
- ],
99
- valueToExport.length > 0 && (() => {
100
- return (_, file) => {
101
- file.data["mdx-export"] ??= [];
102
- for (const name of valueToExport) {
103
- if (!(name in file.data)) continue;
104
- file.data["mdx-export"].push({
105
- name,
106
- value: file.data[name]
107
- });
108
- }
109
- };
110
- })
111
- ],
112
- mdxOptions.remarkPlugins
113
- );
114
- const rehypePlugins = pluginOption(
115
- (v) => [
116
- rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
117
- ...v,
118
- plugins.rehypeToc
119
- ],
120
- mdxOptions.rehypePlugins
121
- );
122
- return {
123
- ...mdxOptions,
124
- outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
125
- remarkPlugins,
126
- rehypePlugins
127
- };
128
- };
51
+ return async (environment = "bundler") => {
52
+ if (options.preset === "minimal") return options;
53
+ const plugins = await import("fumadocs-core/mdx-plugins");
54
+ const { valueToExport = [], rehypeCodeOptions, remarkImageOptions, remarkHeadingOptions, remarkStructureOptions, remarkCodeTabOptions, remarkNpmOptions, ...mdxOptions } = options;
55
+ const remarkPlugins = pluginOption((v) => [
56
+ plugins.remarkGfm,
57
+ [plugins.remarkHeading, {
58
+ generateToc: false,
59
+ ...remarkHeadingOptions
60
+ }],
61
+ remarkImageOptions !== false && [plugins.remarkImage, {
62
+ ...remarkImageOptions,
63
+ useImport: remarkImageOptions?.useImport ?? environment === "bundler"
64
+ }],
65
+ "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [plugins.remarkCodeTab, remarkCodeTabOptions],
66
+ "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
67
+ ...v,
68
+ remarkStructureOptions !== false && [plugins.remarkStructure, {
69
+ exportAs: "structuredData",
70
+ ...remarkStructureOptions
71
+ }],
72
+ valueToExport.length > 0 && (() => {
73
+ return (_, file) => {
74
+ file.data["mdx-export"] ??= [];
75
+ for (const name of valueToExport) {
76
+ if (!(name in file.data)) continue;
77
+ file.data["mdx-export"].push({
78
+ name,
79
+ value: file.data[name]
80
+ });
81
+ }
82
+ };
83
+ })
84
+ ], mdxOptions.remarkPlugins);
85
+ const rehypePlugins = pluginOption((v) => [
86
+ rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
87
+ ...v,
88
+ plugins.rehypeToc
89
+ ], mdxOptions.rehypePlugins);
90
+ return {
91
+ ...mdxOptions,
92
+ outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
93
+ remarkPlugins,
94
+ rehypePlugins
95
+ };
96
+ };
129
97
  }
130
98
 
131
- // src/config/build.ts
132
- var import_node_path = __toESM(require("path"), 1);
133
- var SupportedFormats = {
134
- doc: ["mdx", "md"],
135
- meta: ["json", "yaml"]
99
+ //#endregion
100
+ //#region src/config/build.ts
101
+ const SupportedFormats = {
102
+ doc: ["mdx", "md"],
103
+ meta: ["json", "yaml"]
136
104
  };
137
105
  function buildCollection(name, collection, cwd) {
138
- if (collection.type === "docs") {
139
- return {
140
- ...collection,
141
- type: "docs",
142
- get dir() {
143
- return this.docs.dir;
144
- },
145
- name,
146
- meta: buildCollection(name, collection.meta, cwd),
147
- docs: buildCollection(name, collection.docs, cwd),
148
- hasFile(filePath) {
149
- return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
150
- },
151
- isFileSupported(filePath) {
152
- return this.docs.isFileSupported(filePath) || this.meta.isFileSupported(filePath);
153
- },
154
- cwd
155
- };
156
- }
157
- return {
158
- ...collection,
159
- ...buildPrimitiveCollection(name, collection, cwd)
160
- };
106
+ if (collection.type === "docs") return {
107
+ ...collection,
108
+ type: "docs",
109
+ get dir() {
110
+ return this.docs.dir;
111
+ },
112
+ name,
113
+ meta: buildCollection(name, collection.meta, cwd),
114
+ docs: buildCollection(name, collection.docs, cwd),
115
+ hasFile(filePath) {
116
+ return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
117
+ },
118
+ isFileSupported(filePath) {
119
+ return this.docs.isFileSupported(filePath) || this.meta.isFileSupported(filePath);
120
+ },
121
+ cwd
122
+ };
123
+ return {
124
+ ...collection,
125
+ ...buildPrimitiveCollection(name, collection, cwd)
126
+ };
161
127
  }
162
128
  function buildPrimitiveCollection(name, config, cwd) {
163
- const supportedFormats = SupportedFormats[config.type];
164
- const patterns = config.files ?? [`**/*.{${supportedFormats.join(",")}}`];
165
- let matcher;
166
- return {
167
- dir: import_node_path.default.resolve(cwd, config.dir),
168
- cwd,
169
- name,
170
- patterns,
171
- isFileSupported(filePath) {
172
- return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
173
- },
174
- hasFile(filePath) {
175
- if (!this.isFileSupported(filePath)) return false;
176
- const relativePath = import_node_path.default.relative(this.dir, filePath);
177
- if (relativePath.startsWith(`..${import_node_path.default.sep}`)) return false;
178
- return (matcher ??= (0, import_picomatch.default)(patterns))(relativePath);
179
- }
180
- };
129
+ const supportedFormats = SupportedFormats[config.type];
130
+ const patterns = config.files ?? [`**/*.{${supportedFormats.join(",")}}`];
131
+ let matcher;
132
+ return {
133
+ dir: node_path.default.resolve(cwd, config.dir),
134
+ cwd,
135
+ name,
136
+ patterns,
137
+ isFileSupported(filePath) {
138
+ return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
139
+ },
140
+ hasFile(filePath) {
141
+ if (!this.isFileSupported(filePath)) return false;
142
+ const relativePath = node_path.default.relative(this.dir, filePath);
143
+ if (relativePath.startsWith(`..${node_path.default.sep}`)) return false;
144
+ return (matcher ??= (0, picomatch.default)(patterns))(relativePath);
145
+ }
146
+ };
181
147
  }
182
148
  function buildConfig(config, cwd = process.cwd()) {
183
- const collections = /* @__PURE__ */ new Map();
184
- const loaded = {};
185
- for (const [k, v] of Object.entries(config)) {
186
- if (!v) {
187
- continue;
188
- }
189
- if (typeof v === "object" && "type" in v) {
190
- if (v.type === "docs" || v.type === "doc" || v.type === "meta") {
191
- collections.set(k, buildCollection(k, v, cwd));
192
- continue;
193
- }
194
- }
195
- if (k === "default" && v) {
196
- Object.assign(loaded, v);
197
- continue;
198
- }
199
- throw new Error(
200
- `Unknown export "${k}", you can only export collections from source configuration file.`
201
- );
202
- }
203
- const mdxOptionsCache = /* @__PURE__ */ new Map();
204
- return {
205
- global: loaded,
206
- collections,
207
- workspaces: Object.fromEntries(
208
- Object.entries(loaded.workspaces ?? {}).map(([key, value]) => {
209
- return [
210
- key,
211
- {
212
- dir: value.dir,
213
- config: buildConfig(value.config, import_node_path.default.resolve(cwd, value.dir))
214
- }
215
- ];
216
- })
217
- ),
218
- getMDXOptions(collection, environment = "bundler") {
219
- const key = collection ? `${environment}:${collection.name}` : environment;
220
- const cached = mdxOptionsCache.get(key);
221
- if (cached) return cached;
222
- let result;
223
- if (collection?.mdxOptions) {
224
- const optionsFn = collection.mdxOptions;
225
- result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
226
- } else {
227
- result = (async () => {
228
- const optionsFn = this.global.mdxOptions;
229
- const options = typeof optionsFn === "function" ? await optionsFn() : optionsFn;
230
- return applyMdxPreset(options)(environment);
231
- })();
232
- }
233
- mdxOptionsCache.set(key, result);
234
- return result;
235
- }
236
- };
149
+ const collections = /* @__PURE__ */ new Map();
150
+ const loaded = {};
151
+ for (const [k, v] of Object.entries(config)) {
152
+ if (!v) continue;
153
+ if (typeof v === "object" && "type" in v) {
154
+ if (v.type === "docs" || v.type === "doc" || v.type === "meta") {
155
+ collections.set(k, buildCollection(k, v, cwd));
156
+ continue;
157
+ }
158
+ }
159
+ if (k === "default" && v) {
160
+ Object.assign(loaded, v);
161
+ continue;
162
+ }
163
+ throw new Error(`Unknown export "${k}", you can only export collections from source configuration file.`);
164
+ }
165
+ const mdxOptionsCache = /* @__PURE__ */ new Map();
166
+ return {
167
+ global: loaded,
168
+ collections,
169
+ workspaces: Object.fromEntries(Object.entries(loaded.workspaces ?? {}).map(([key, value]) => {
170
+ return [key, {
171
+ dir: value.dir,
172
+ config: buildConfig(value.config, node_path.default.resolve(cwd, value.dir))
173
+ }];
174
+ })),
175
+ getMDXOptions(collection, environment = "bundler") {
176
+ const key = collection ? `${environment}:${collection.name}` : environment;
177
+ const cached = mdxOptionsCache.get(key);
178
+ if (cached) return cached;
179
+ let result;
180
+ if (collection?.mdxOptions) {
181
+ const optionsFn = collection.mdxOptions;
182
+ result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
183
+ } else result = (async () => {
184
+ const optionsFn = this.global.mdxOptions;
185
+ return applyMdxPreset(typeof optionsFn === "function" ? await optionsFn() : optionsFn)(environment);
186
+ })();
187
+ mdxOptionsCache.set(key, result);
188
+ return result;
189
+ }
190
+ };
237
191
  }
238
192
 
239
- // src/config/load-from-file.ts
193
+ //#endregion
194
+ //#region src/config/load-from-file.ts
240
195
  async function compileConfig(core) {
241
- const { build } = await import("esbuild");
242
- const { configPath, outDir } = core.getOptions();
243
- const transformed = await build({
244
- entryPoints: [{ in: configPath, out: "source.config" }],
245
- bundle: true,
246
- outdir: outDir,
247
- target: "node20",
248
- write: true,
249
- platform: "node",
250
- format: "esm",
251
- packages: "external",
252
- outExtension: {
253
- ".js": ".mjs"
254
- },
255
- allowOverwrite: true
256
- });
257
- if (transformed.errors.length > 0) {
258
- throw new Error("failed to compile configuration file");
259
- }
196
+ const { build } = await import("esbuild");
197
+ const { configPath, outDir } = core.getOptions();
198
+ if ((await build({
199
+ entryPoints: [{
200
+ in: configPath,
201
+ out: "source.config"
202
+ }],
203
+ bundle: true,
204
+ outdir: outDir,
205
+ target: "node20",
206
+ write: true,
207
+ platform: "node",
208
+ format: "esm",
209
+ packages: "external",
210
+ outExtension: { ".js": ".mjs" },
211
+ allowOverwrite: true
212
+ })).errors.length > 0) throw new Error("failed to compile configuration file");
260
213
  }
214
+ /**
215
+ * Load config
216
+ *
217
+ * @param build - By default, it assumes the config file has been compiled. Set this `true` to compile the config first.
218
+ */
261
219
  async function loadConfig(core, build = false) {
262
- if (build) await compileConfig(core);
263
- const url = (0, import_node_url.pathToFileURL)(core.getCompiledConfigPath());
264
- url.searchParams.set("hash", Date.now().toString());
265
- const config = import(url.href).then(
266
- (loaded) => buildConfig(loaded)
267
- );
268
- return await config;
220
+ if (build) await compileConfig(core);
221
+ const url = (0, node_url.pathToFileURL)(core.getCompiledConfigPath());
222
+ url.searchParams.set("hash", Date.now().toString());
223
+ return await import(url.href).then((loaded) => buildConfig(loaded));
269
224
  }
270
225
 
271
- // src/core.ts
272
- var import_node_path3 = __toESM(require("path"), 1);
273
- var import_promises = __toESM(require("fs/promises"), 1);
274
-
275
- // src/utils/validation.ts
226
+ //#endregion
227
+ //#region src/utils/validation.ts
276
228
  var ValidationError = class extends Error {
277
- constructor(message, issues) {
278
- super(
279
- `${message}:
280
- ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
281
- );
282
- this.title = message;
283
- this.issues = issues;
284
- }
285
- async toStringFormatted() {
286
- const picocolorsModule = await import("picocolors");
287
- const picocolors = picocolorsModule.default ?? picocolorsModule;
288
- return [
289
- picocolors.bold(`[MDX] ${this.title}:`),
290
- ...this.issues.map(
291
- (issue) => picocolors.redBright(
292
- `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
293
- )
294
- )
295
- ].join("\n");
296
- }
229
+ constructor(message, issues) {
230
+ super(`${message}:\n${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`);
231
+ this.title = message;
232
+ this.issues = issues;
233
+ }
234
+ async toStringFormatted() {
235
+ const picocolorsModule = await import("picocolors");
236
+ const picocolors = picocolorsModule.default ?? picocolorsModule;
237
+ return [picocolors.bold(`[MDX] ${this.title}:`), ...this.issues.map((issue) => picocolors.redBright(`- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`))].join("\n");
238
+ }
297
239
  };
298
240
  async function validate(schema, data, context, errorMessage) {
299
- if (typeof schema === "function" && !("~standard" in schema)) {
300
- schema = schema(context);
301
- }
302
- if ("~standard" in schema) {
303
- const result = await schema["~standard"].validate(
304
- data
305
- );
306
- if (result.issues) {
307
- throw new ValidationError(errorMessage, result.issues);
308
- }
309
- return result.value;
310
- }
311
- return data;
241
+ if (typeof schema === "function" && !("~standard" in schema)) schema = schema(context);
242
+ if ("~standard" in schema) {
243
+ const result = await schema["~standard"].validate(data);
244
+ if (result.issues) throw new ValidationError(errorMessage, result.issues);
245
+ return result.value;
246
+ }
247
+ return data;
312
248
  }
313
249
 
314
- // src/utils/codegen.ts
315
- var import_node_path2 = __toESM(require("path"), 1);
316
- var import_tinyglobby = require("tinyglobby");
317
- function createCodegen({
318
- target = "default",
319
- outDir = "",
320
- jsExtension = false,
321
- globCache = /* @__PURE__ */ new Map()
322
- }) {
323
- let eagerImportId = 0;
324
- const banner = ["// @ts-nocheck"];
325
- if (target === "vite") {
326
- banner.push('/// <reference types="vite/client" />');
327
- }
328
- return {
329
- options: {
330
- target,
331
- outDir
332
- },
333
- lines: [],
334
- addImport(statement) {
335
- this.lines.unshift(statement);
336
- },
337
- async pushAsync(insert) {
338
- for (const line of await Promise.all(insert)) {
339
- if (line === void 0) continue;
340
- this.lines.push(line);
341
- }
342
- },
343
- async generateGlobImport(patterns, options) {
344
- if (target === "vite") {
345
- return this.generateViteGlobImport(patterns, options);
346
- }
347
- return this.generateNodeGlobImport(patterns, options);
348
- },
349
- generateViteGlobImport(patterns, { base, ...rest }) {
350
- patterns = (typeof patterns === "string" ? [patterns] : patterns).map(
351
- normalizeViteGlobPath
352
- );
353
- return `import.meta.glob(${JSON.stringify(patterns)}, ${JSON.stringify(
354
- {
355
- base: normalizeViteGlobPath(import_node_path2.default.relative(outDir, base)),
356
- ...rest
357
- },
358
- null,
359
- 2
360
- )})`;
361
- },
362
- async generateNodeGlobImport(patterns, {
363
- base,
364
- eager = false,
365
- query = {},
366
- import: importName
367
- }) {
368
- const cacheKey = JSON.stringify({ patterns, base });
369
- let files = globCache.get(cacheKey);
370
- if (!files) {
371
- files = (0, import_tinyglobby.glob)(patterns, {
372
- cwd: base
373
- });
374
- globCache.set(cacheKey, files);
375
- }
376
- let code = "{";
377
- for (const item of await files) {
378
- const fullPath = import_node_path2.default.join(base, item);
379
- const searchParams = new URLSearchParams();
380
- for (const [k, v] of Object.entries(query)) {
381
- if (v !== void 0) searchParams.set(k, v);
382
- }
383
- const importPath = this.formatImportPath(fullPath) + "?" + searchParams.toString();
384
- if (eager) {
385
- const name = `__fd_glob_${eagerImportId++}`;
386
- this.lines.unshift(
387
- importName ? `import { ${importName} as ${name} } from ${JSON.stringify(importPath)}` : `import * as ${name} from ${JSON.stringify(importPath)}`
388
- );
389
- code += `${JSON.stringify(item)}: ${name}, `;
390
- } else {
391
- let line = `${JSON.stringify(item)}: () => import(${JSON.stringify(importPath)})`;
392
- if (importName) {
393
- line += `.then(mod => mod.${importName})`;
394
- }
395
- code += `${line}, `;
396
- }
397
- }
398
- code += "}";
399
- return code;
400
- },
401
- formatImportPath(file) {
402
- const ext = import_node_path2.default.extname(file);
403
- let filename;
404
- if (ext === ".ts") {
405
- filename = file.substring(0, file.length - ext.length);
406
- if (jsExtension) filename += ".js";
407
- } else {
408
- filename = file;
409
- }
410
- const importPath = slash(import_node_path2.default.relative(outDir, filename));
411
- return importPath.startsWith(".") ? importPath : `./${importPath}`;
412
- },
413
- toString() {
414
- return [...banner, ...this.lines].join("\n");
415
- }
416
- };
250
+ //#endregion
251
+ //#region src/utils/codegen.ts
252
+ /**
253
+ * Code generator (one instance per file)
254
+ */
255
+ function createCodegen({ target = "default", outDir = "", jsExtension = false, globCache = /* @__PURE__ */ new Map() }) {
256
+ let eagerImportId = 0;
257
+ const banner = ["// @ts-nocheck"];
258
+ if (target === "vite") banner.push("/// <reference types=\"vite/client\" />");
259
+ return {
260
+ options: {
261
+ target,
262
+ outDir
263
+ },
264
+ lines: [],
265
+ addImport(statement) {
266
+ this.lines.unshift(statement);
267
+ },
268
+ async pushAsync(insert) {
269
+ for (const line of await Promise.all(insert)) {
270
+ if (line === void 0) continue;
271
+ this.lines.push(line);
272
+ }
273
+ },
274
+ async generateGlobImport(patterns, options) {
275
+ if (target === "vite") return this.generateViteGlobImport(patterns, options);
276
+ return this.generateNodeGlobImport(patterns, options);
277
+ },
278
+ generateViteGlobImport(patterns, { base, ...rest }) {
279
+ patterns = (typeof patterns === "string" ? [patterns] : patterns).map(normalizeViteGlobPath);
280
+ return `import.meta.glob(${JSON.stringify(patterns)}, ${JSON.stringify({
281
+ base: normalizeViteGlobPath(node_path.default.relative(outDir, base)),
282
+ ...rest
283
+ }, null, 2)})`;
284
+ },
285
+ async generateNodeGlobImport(patterns, { base, eager = false, query = {}, import: importName }) {
286
+ const cacheKey = JSON.stringify({
287
+ patterns,
288
+ base
289
+ });
290
+ let files = globCache.get(cacheKey);
291
+ if (!files) {
292
+ files = (0, tinyglobby.glob)(patterns, { cwd: base });
293
+ globCache.set(cacheKey, files);
294
+ }
295
+ let code = "{";
296
+ for (const item of await files) {
297
+ const fullPath = node_path.default.join(base, item);
298
+ const searchParams = new URLSearchParams();
299
+ for (const [k, v] of Object.entries(query)) if (v !== void 0) searchParams.set(k, v);
300
+ const importPath = this.formatImportPath(fullPath) + "?" + searchParams.toString();
301
+ if (eager) {
302
+ const name = `__fd_glob_${eagerImportId++}`;
303
+ this.lines.unshift(importName ? `import { ${importName} as ${name} } from ${JSON.stringify(importPath)}` : `import * as ${name} from ${JSON.stringify(importPath)}`);
304
+ code += `${JSON.stringify(item)}: ${name}, `;
305
+ } else {
306
+ let line = `${JSON.stringify(item)}: () => import(${JSON.stringify(importPath)})`;
307
+ if (importName) line += `.then(mod => mod.${importName})`;
308
+ code += `${line}, `;
309
+ }
310
+ }
311
+ code += "}";
312
+ return code;
313
+ },
314
+ formatImportPath(file) {
315
+ const ext = node_path.default.extname(file);
316
+ let filename;
317
+ if (ext === ".ts") {
318
+ filename = file.substring(0, file.length - ext.length);
319
+ if (jsExtension) filename += ".js";
320
+ } else filename = file;
321
+ const importPath = slash(node_path.default.relative(outDir, filename));
322
+ return importPath.startsWith(".") ? importPath : `./${importPath}`;
323
+ },
324
+ toString() {
325
+ return [...banner, ...this.lines].join("\n");
326
+ }
327
+ };
417
328
  }
329
+ /**
330
+ * convert into POSIX & relative file paths, such that Vite can accept it.
331
+ */
418
332
  function normalizeViteGlobPath(file) {
419
- file = slash(file);
420
- if (file.startsWith("./")) return file;
421
- if (file.startsWith("/")) return `.${file}`;
422
- return `./${file}`;
333
+ file = slash(file);
334
+ if (file.startsWith("./")) return file;
335
+ if (file.startsWith("/")) return `.${file}`;
336
+ return `./${file}`;
423
337
  }
424
- function slash(path7) {
425
- const isExtendedLengthPath = path7.startsWith("\\\\?\\");
426
- if (isExtendedLengthPath) {
427
- return path7;
428
- }
429
- return path7.replaceAll("\\", "/");
338
+ function slash(path$6) {
339
+ if (path$6.startsWith("\\\\?\\")) return path$6;
340
+ return path$6.replaceAll("\\", "/");
430
341
  }
431
342
  function ident(code, tab = 1) {
432
- return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
343
+ return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
433
344
  }
434
345
 
435
- // src/core.ts
436
- var _Defaults = {
437
- configPath: "source.config.ts",
438
- outDir: ".source"
346
+ //#endregion
347
+ //#region src/core.ts
348
+ const _Defaults = {
349
+ configPath: "source.config.ts",
350
+ outDir: ".source"
439
351
  };
440
352
  async function getPlugins(pluginOptions) {
441
- const plugins = [];
442
- for await (const option of pluginOptions) {
443
- if (!option) continue;
444
- if (Array.isArray(option)) plugins.push(...await getPlugins(option));
445
- else plugins.push(option);
446
- }
447
- return plugins;
353
+ const plugins = [];
354
+ for await (const option of pluginOptions) {
355
+ if (!option) continue;
356
+ if (Array.isArray(option)) plugins.push(...await getPlugins(option));
357
+ else plugins.push(option);
358
+ }
359
+ return plugins;
448
360
  }
449
361
  function createCore(options) {
450
- let config;
451
- let plugins;
452
- const workspaces = /* @__PURE__ */ new Map();
453
- async function transformMetadata({
454
- collection,
455
- filePath,
456
- source
457
- }, data) {
458
- if (collection.schema) {
459
- data = await validate(
460
- collection.schema,
461
- data,
462
- { path: filePath, source },
463
- collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
464
- );
465
- }
466
- return data;
467
- }
468
- return {
469
- /**
470
- * Convenient cache store, reset when config changes
471
- */
472
- cache: /* @__PURE__ */ new Map(),
473
- async init({ config: newConfig }) {
474
- config = await newConfig;
475
- this.cache.clear();
476
- workspaces.clear();
477
- plugins = await getPlugins([
478
- postprocessPlugin(),
479
- options.plugins,
480
- config.global.plugins
481
- ]);
482
- for (const plugin of plugins) {
483
- const out = await plugin.config?.call(this.getPluginContext(), config);
484
- if (out) config = out;
485
- }
486
- if (!options.workspace) {
487
- await Promise.all(
488
- Object.entries(config.workspaces).map(async ([name, workspace]) => {
489
- const core = createCore({
490
- ...options,
491
- outDir: import_node_path3.default.join(options.outDir, name),
492
- workspace: {
493
- name,
494
- parent: this,
495
- dir: workspace.dir
496
- }
497
- });
498
- await core.init({ config: workspace.config });
499
- workspaces.set(name, core);
500
- })
501
- );
502
- }
503
- },
504
- getWorkspaces() {
505
- return workspaces;
506
- },
507
- getOptions() {
508
- return options;
509
- },
510
- getConfig() {
511
- return config;
512
- },
513
- /**
514
- * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
515
- */
516
- getCompiledConfigPath() {
517
- return import_node_path3.default.join(options.outDir, "source.config.mjs");
518
- },
519
- getPlugins() {
520
- return plugins;
521
- },
522
- getCollections() {
523
- return Array.from(config.collections.values());
524
- },
525
- getCollection(name) {
526
- return config.collections.get(name);
527
- },
528
- getPluginContext() {
529
- return {
530
- core: this
531
- };
532
- },
533
- async initServer(server) {
534
- const ctx = this.getPluginContext();
535
- for (const plugin of plugins) {
536
- await plugin.configureServer?.call(ctx, server);
537
- }
538
- for (const workspace of workspaces.values()) {
539
- await workspace.initServer(server);
540
- }
541
- },
542
- async emit(emitOptions = {}) {
543
- const { filterPlugin, filterWorkspace, write = false } = emitOptions;
544
- const start = performance.now();
545
- const ctx = this.getPluginContext();
546
- const added = /* @__PURE__ */ new Set();
547
- const out = {
548
- entries: [],
549
- workspaces: {}
550
- };
551
- for (const li of await Promise.all(
552
- plugins.map((plugin) => {
553
- if (filterPlugin && !filterPlugin(plugin) || !plugin.emit) return;
554
- return plugin.emit.call(ctx);
555
- })
556
- )) {
557
- if (!li) continue;
558
- for (const item of li) {
559
- if (added.has(item.path)) continue;
560
- out.entries.push(item);
561
- added.add(item.path);
562
- }
563
- }
564
- if (write) {
565
- await Promise.all(
566
- out.entries.map(async (entry) => {
567
- const file = import_node_path3.default.join(options.outDir, entry.path);
568
- await import_promises.default.mkdir(import_node_path3.default.dirname(file), { recursive: true });
569
- await import_promises.default.writeFile(file, entry.content);
570
- })
571
- );
572
- console.log(
573
- options.workspace ? `[MDX: ${options.workspace.name}] generated files in ${performance.now() - start}ms` : `[MDX] generated files in ${performance.now() - start}ms`
574
- );
575
- }
576
- for (const [name, workspace] of workspaces) {
577
- if (filterWorkspace && !filterWorkspace(name)) continue;
578
- out.workspaces[name] = (await workspace.emit(emitOptions)).entries;
579
- }
580
- return out;
581
- },
582
- async transformMeta(options2, data) {
583
- const ctx = {
584
- ...this.getPluginContext(),
585
- ...options2
586
- };
587
- data = await transformMetadata(options2, data);
588
- for (const plugin of plugins) {
589
- if (plugin.meta?.transform)
590
- data = await plugin.meta.transform.call(ctx, data) ?? data;
591
- }
592
- return data;
593
- },
594
- async transformFrontmatter(options2, data) {
595
- const ctx = {
596
- ...this.getPluginContext(),
597
- ...options2
598
- };
599
- data = await transformMetadata(options2, data);
600
- for (const plugin of plugins) {
601
- if (plugin.doc?.frontmatter)
602
- data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
603
- }
604
- return data;
605
- },
606
- async transformVFile(options2, file) {
607
- const ctx = {
608
- ...this.getPluginContext(),
609
- ...options2
610
- };
611
- for (const plugin of plugins) {
612
- if (plugin.doc?.vfile)
613
- file = await plugin.doc.vfile.call(ctx, file) ?? file;
614
- }
615
- return file;
616
- }
617
- };
362
+ let config;
363
+ let plugins;
364
+ const workspaces = /* @__PURE__ */ new Map();
365
+ async function transformMetadata({ collection, filePath, source }, data) {
366
+ if (collection.schema) data = await validate(collection.schema, data, {
367
+ path: filePath,
368
+ source
369
+ }, collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`);
370
+ return data;
371
+ }
372
+ return {
373
+ cache: /* @__PURE__ */ new Map(),
374
+ async init({ config: newConfig }) {
375
+ config = await newConfig;
376
+ this.cache.clear();
377
+ workspaces.clear();
378
+ plugins = await getPlugins([
379
+ postprocessPlugin(),
380
+ options.plugins,
381
+ config.global.plugins
382
+ ]);
383
+ for (const plugin of plugins) {
384
+ const out = await plugin.config?.call(this.getPluginContext(), config);
385
+ if (out) config = out;
386
+ }
387
+ if (!options.workspace) await Promise.all(Object.entries(config.workspaces).map(async ([name, workspace]) => {
388
+ const core = createCore({
389
+ ...options,
390
+ outDir: node_path.default.join(options.outDir, name),
391
+ workspace: {
392
+ name,
393
+ parent: this,
394
+ dir: workspace.dir
395
+ }
396
+ });
397
+ await core.init({ config: workspace.config });
398
+ workspaces.set(name, core);
399
+ }));
400
+ },
401
+ getWorkspaces() {
402
+ return workspaces;
403
+ },
404
+ getOptions() {
405
+ return options;
406
+ },
407
+ getConfig() {
408
+ return config;
409
+ },
410
+ getCompiledConfigPath() {
411
+ return node_path.default.join(options.outDir, "source.config.mjs");
412
+ },
413
+ getPlugins() {
414
+ return plugins;
415
+ },
416
+ getCollections() {
417
+ return Array.from(config.collections.values());
418
+ },
419
+ getCollection(name) {
420
+ return config.collections.get(name);
421
+ },
422
+ getPluginContext() {
423
+ return { core: this };
424
+ },
425
+ async initServer(server) {
426
+ const ctx = this.getPluginContext();
427
+ for (const plugin of plugins) await plugin.configureServer?.call(ctx, server);
428
+ for (const workspace of workspaces.values()) await workspace.initServer(server);
429
+ },
430
+ async emit(emitOptions = {}) {
431
+ const { filterPlugin, filterWorkspace, write = false } = emitOptions;
432
+ const start = performance.now();
433
+ const ctx = this.getPluginContext();
434
+ const added = /* @__PURE__ */ new Set();
435
+ const out = {
436
+ entries: [],
437
+ workspaces: {}
438
+ };
439
+ for (const li of await Promise.all(plugins.map((plugin) => {
440
+ if (filterPlugin && !filterPlugin(plugin) || !plugin.emit) return;
441
+ return plugin.emit.call(ctx);
442
+ }))) {
443
+ if (!li) continue;
444
+ for (const item of li) {
445
+ if (added.has(item.path)) continue;
446
+ out.entries.push(item);
447
+ added.add(item.path);
448
+ }
449
+ }
450
+ if (write) {
451
+ await Promise.all(out.entries.map(async (entry) => {
452
+ const file = node_path.default.join(options.outDir, entry.path);
453
+ await node_fs_promises.default.mkdir(node_path.default.dirname(file), { recursive: true });
454
+ await node_fs_promises.default.writeFile(file, entry.content);
455
+ }));
456
+ console.log(options.workspace ? `[MDX: ${options.workspace.name}] generated files in ${performance.now() - start}ms` : `[MDX] generated files in ${performance.now() - start}ms`);
457
+ }
458
+ for (const [name, workspace] of workspaces) {
459
+ if (filterWorkspace && !filterWorkspace(name)) continue;
460
+ out.workspaces[name] = (await workspace.emit(emitOptions)).entries;
461
+ }
462
+ return out;
463
+ },
464
+ async transformMeta(options$1, data) {
465
+ const ctx = {
466
+ ...this.getPluginContext(),
467
+ ...options$1
468
+ };
469
+ data = await transformMetadata(options$1, data);
470
+ for (const plugin of plugins) if (plugin.meta?.transform) data = await plugin.meta.transform.call(ctx, data) ?? data;
471
+ return data;
472
+ },
473
+ async transformFrontmatter(options$1, data) {
474
+ const ctx = {
475
+ ...this.getPluginContext(),
476
+ ...options$1
477
+ };
478
+ data = await transformMetadata(options$1, data);
479
+ for (const plugin of plugins) if (plugin.doc?.frontmatter) data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
480
+ return data;
481
+ },
482
+ async transformVFile(options$1, file) {
483
+ const ctx = {
484
+ ...this.getPluginContext(),
485
+ ...options$1
486
+ };
487
+ for (const plugin of plugins) if (plugin.doc?.vfile) file = await plugin.doc.vfile.call(ctx, file) ?? file;
488
+ return file;
489
+ }
490
+ };
618
491
  }
619
492
  function postprocessPlugin() {
620
- const LinkReferenceTypes = `{
493
+ const LinkReferenceTypes = `{
621
494
  /**
622
495
  * extracted references (e.g. hrefs, paths), useful for analyzing relationships between pages.
623
496
  */
624
497
  extractedReferences: import("fumadocs-mdx").ExtractedReference[];
625
498
  }`;
626
- return {
627
- "index-file": {
628
- generateTypeConfig() {
629
- const lines = [];
630
- lines.push("{");
631
- lines.push(" DocData: {");
632
- for (const collection of this.core.getCollections()) {
633
- let postprocessOptions;
634
- switch (collection.type) {
635
- case "doc":
636
- postprocessOptions = collection.postprocess;
637
- break;
638
- case "docs":
639
- postprocessOptions = collection.docs.postprocess;
640
- break;
641
- }
642
- if (postprocessOptions?.extractLinkReferences) {
643
- lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
644
- }
645
- }
646
- lines.push(" }");
647
- lines.push("}");
648
- return lines.join("\n");
649
- },
650
- serverOptions(options) {
651
- options.doc ??= {};
652
- options.doc.passthroughs ??= [];
653
- options.doc.passthroughs.push("extractedReferences");
654
- }
655
- }
656
- };
499
+ return { "index-file": {
500
+ generateTypeConfig() {
501
+ const lines = [];
502
+ lines.push("{");
503
+ lines.push(" DocData: {");
504
+ for (const collection of this.core.getCollections()) {
505
+ let postprocessOptions;
506
+ switch (collection.type) {
507
+ case "doc":
508
+ postprocessOptions = collection.postprocess;
509
+ break;
510
+ case "docs":
511
+ postprocessOptions = collection.docs.postprocess;
512
+ break;
513
+ }
514
+ if (postprocessOptions?.extractLinkReferences) lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
515
+ }
516
+ lines.push(" }");
517
+ lines.push("}");
518
+ return lines.join("\n");
519
+ },
520
+ serverOptions(options) {
521
+ options.doc ??= {};
522
+ options.doc.passthroughs ??= [];
523
+ options.doc.passthroughs.push("extractedReferences");
524
+ }
525
+ } };
657
526
  }
658
527
 
659
- // src/loaders/index.ts
660
- var metaLoaderGlob = /\.(json|yaml)(\?.+?)?$/;
661
- var mdxLoaderGlob = /\.mdx?(\?.+?)?$/;
528
+ //#endregion
529
+ //#region src/loaders/index.ts
530
+ const metaLoaderGlob = /\.(json|yaml)(\?.+?)?$/;
531
+ const mdxLoaderGlob = /\.mdx?(\?.+?)?$/;
662
532
 
663
- // src/plugins/index-file.ts
664
- var import_path = __toESM(require("path"), 1);
665
- var import_tinyglobby2 = require("tinyglobby");
666
-
667
- // src/utils/fs-cache.ts
668
- var import_promises2 = __toESM(require("fs/promises"), 1);
669
- var import_node_path4 = __toESM(require("path"), 1);
670
- var map = /* @__PURE__ */ new Map();
533
+ //#endregion
534
+ //#region src/utils/fs-cache.ts
535
+ const map = /* @__PURE__ */ new Map();
671
536
  function createFSCache() {
672
- return {
673
- read(file) {
674
- const fullPath = toFullPath(file);
675
- const cached = map.get(fullPath);
676
- if (cached) return cached;
677
- const read = import_promises2.default.readFile(fullPath).then((s) => s.toString());
678
- map.set(fullPath, read);
679
- return read;
680
- },
681
- delete(file) {
682
- map.delete(toFullPath(file));
683
- }
684
- };
537
+ return {
538
+ read(file) {
539
+ const fullPath = toFullPath(file);
540
+ const cached = map.get(fullPath);
541
+ if (cached) return cached;
542
+ const read = node_fs_promises.default.readFile(fullPath).then((s) => s.toString());
543
+ map.set(fullPath, read);
544
+ return read;
545
+ },
546
+ delete(file) {
547
+ map.delete(toFullPath(file));
548
+ }
549
+ };
685
550
  }
551
+ /**
552
+ * make file paths relative to cwd
553
+ */
686
554
  function toFullPath(file) {
687
- if (import_node_path4.default.isAbsolute(file)) {
688
- return import_node_path4.default.relative(process.cwd(), file);
689
- }
690
- return file;
555
+ if (node_path.default.isAbsolute(file)) return node_path.default.relative(process.cwd(), file);
556
+ return file;
691
557
  }
692
558
 
693
- // src/plugins/index-file.ts
694
- var import_crypto = require("crypto");
695
-
696
- // src/utils/fuma-matter.ts
697
- var import_js_yaml = require("js-yaml");
698
- var regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
559
+ //#endregion
560
+ //#region src/utils/fuma-matter.ts
561
+ /**
562
+ * Inspired by https://github.com/jonschlinkert/gray-matter
563
+ */
564
+ const regex = /^---\r?\n(.+?)\r?\n---\r?\n?/s;
565
+ /**
566
+ * parse frontmatter, it supports only yaml format
567
+ */
699
568
  function fumaMatter(input) {
700
- const output = { matter: "", data: {}, content: input };
701
- const match = regex.exec(input);
702
- if (!match) {
703
- return output;
704
- }
705
- output.matter = match[0];
706
- output.content = input.slice(match[0].length);
707
- const loaded = (0, import_js_yaml.load)(match[1]);
708
- output.data = loaded ?? {};
709
- return output;
569
+ const output = {
570
+ matter: "",
571
+ data: {},
572
+ content: input
573
+ };
574
+ const match = regex.exec(input);
575
+ if (!match) return output;
576
+ output.matter = match[0];
577
+ output.content = input.slice(match[0].length);
578
+ output.data = (0, js_yaml.load)(match[1]) ?? {};
579
+ return output;
710
580
  }
711
581
 
712
- // src/plugins/index-file.ts
713
- var indexFileCache = createFSCache();
582
+ //#endregion
583
+ //#region src/plugins/index-file.ts
584
+ const indexFileCache = createFSCache();
714
585
  function indexFile(options = {}) {
715
- const {
716
- target = "default",
717
- addJsExtension,
718
- browser = true,
719
- dynamic = true
720
- } = options;
721
- let dynamicCollections;
722
- function isDynamic(collection) {
723
- return collection.type === "docs" && collection.docs.dynamic || collection.type === "doc" && collection.dynamic;
724
- }
725
- function generateConfigs(core) {
726
- const serverOptions = {};
727
- const typeConfigs = [
728
- 'import("fumadocs-mdx/runtime/types").InternalTypeConfig'
729
- ];
730
- const ctx = core.getPluginContext();
731
- for (const plugin of core.getPlugins()) {
732
- const indexFilePlugin = plugin["index-file"];
733
- if (!indexFilePlugin) continue;
734
- indexFilePlugin.serverOptions?.call(ctx, serverOptions);
735
- const config = indexFilePlugin.generateTypeConfig?.call(ctx);
736
- if (config) typeConfigs.push(config);
737
- }
738
- return {
739
- serverOptions,
740
- tc: typeConfigs.join(" & ")
741
- };
742
- }
743
- return {
744
- name: "index-file",
745
- config() {
746
- dynamicCollections = this.core.getCollections().filter(isDynamic);
747
- },
748
- configureServer(server) {
749
- if (!server.watcher) return;
750
- server.watcher.on("all", async (event, file) => {
751
- indexFileCache.delete(file);
752
- if (dynamicCollections.length === 0) {
753
- if (target === "vite") return;
754
- if (target === "default" && event === "change") return;
755
- }
756
- const updatedCollection = this.core.getCollections().find((collection) => collection.hasFile(file));
757
- if (!updatedCollection) return;
758
- if (!isDynamic(updatedCollection)) {
759
- if (target === "vite") return;
760
- if (target === "default" && event === "change") return;
761
- }
762
- await this.core.emit({
763
- filterPlugin: (plugin) => plugin.name === "index-file",
764
- filterWorkspace: () => false,
765
- write: true
766
- });
767
- });
768
- },
769
- async emit() {
770
- const globCache = /* @__PURE__ */ new Map();
771
- const { workspace, outDir } = this.core.getOptions();
772
- const { serverOptions, tc } = generateConfigs(this.core);
773
- const toEmitEntry = async (path7, content) => {
774
- const codegen = createCodegen({
775
- target,
776
- outDir,
777
- jsExtension: addJsExtension,
778
- globCache
779
- });
780
- await content({
781
- core: this.core,
782
- codegen,
783
- serverOptions,
784
- tc,
785
- workspace: workspace?.name
786
- });
787
- return {
788
- path: path7,
789
- content: codegen.toString()
790
- };
791
- };
792
- const out = [
793
- toEmitEntry("server.ts", generateServerIndexFile)
794
- ];
795
- if (dynamic)
796
- out.push(toEmitEntry("dynamic.ts", generateDynamicIndexFile));
797
- if (browser)
798
- out.push(toEmitEntry("browser.ts", generateBrowserIndexFile));
799
- return await Promise.all(out);
800
- }
801
- };
586
+ const { target = "default", addJsExtension, browser = true, dynamic = true } = options;
587
+ let dynamicCollections;
588
+ function isDynamic(collection) {
589
+ return collection.type === "docs" && collection.docs.dynamic || collection.type === "doc" && collection.dynamic;
590
+ }
591
+ function generateConfigs(core) {
592
+ const serverOptions = {};
593
+ const typeConfigs = ["import(\"fumadocs-mdx/runtime/types\").InternalTypeConfig"];
594
+ const ctx = core.getPluginContext();
595
+ for (const plugin of core.getPlugins()) {
596
+ const indexFilePlugin = plugin["index-file"];
597
+ if (!indexFilePlugin) continue;
598
+ indexFilePlugin.serverOptions?.call(ctx, serverOptions);
599
+ const config = indexFilePlugin.generateTypeConfig?.call(ctx);
600
+ if (config) typeConfigs.push(config);
601
+ }
602
+ return {
603
+ serverOptions,
604
+ tc: typeConfigs.join(" & ")
605
+ };
606
+ }
607
+ return {
608
+ name: "index-file",
609
+ config() {
610
+ dynamicCollections = this.core.getCollections().filter(isDynamic);
611
+ },
612
+ configureServer(server) {
613
+ if (!server.watcher) return;
614
+ server.watcher.on("all", async (event, file) => {
615
+ indexFileCache.delete(file);
616
+ if (dynamicCollections.length === 0) {
617
+ if (target === "vite") return;
618
+ if (target === "default" && event === "change") return;
619
+ }
620
+ const updatedCollection = this.core.getCollections().find((collection) => collection.hasFile(file));
621
+ if (!updatedCollection) return;
622
+ if (!isDynamic(updatedCollection)) {
623
+ if (target === "vite") return;
624
+ if (target === "default" && event === "change") return;
625
+ }
626
+ await this.core.emit({
627
+ filterPlugin: (plugin) => plugin.name === "index-file",
628
+ filterWorkspace: () => false,
629
+ write: true
630
+ });
631
+ });
632
+ },
633
+ async emit() {
634
+ const globCache = /* @__PURE__ */ new Map();
635
+ const { workspace, outDir } = this.core.getOptions();
636
+ const { serverOptions, tc } = generateConfigs(this.core);
637
+ const toEmitEntry = async (path$6, content) => {
638
+ const codegen = createCodegen({
639
+ target,
640
+ outDir,
641
+ jsExtension: addJsExtension,
642
+ globCache
643
+ });
644
+ await content({
645
+ core: this.core,
646
+ codegen,
647
+ serverOptions,
648
+ tc,
649
+ workspace: workspace?.name
650
+ });
651
+ return {
652
+ path: path$6,
653
+ content: codegen.toString()
654
+ };
655
+ };
656
+ const out = [toEmitEntry("server.ts", generateServerIndexFile)];
657
+ if (dynamic) out.push(toEmitEntry("dynamic.ts", generateDynamicIndexFile));
658
+ if (browser) out.push(toEmitEntry("browser.ts", generateBrowserIndexFile));
659
+ return await Promise.all(out);
660
+ }
661
+ };
802
662
  }
803
663
  async function generateServerIndexFile(ctx) {
804
- const { core, codegen, serverOptions, tc } = ctx;
805
- codegen.lines.push(
806
- `import { server } from 'fumadocs-mdx/runtime/server';`,
807
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
808
- "",
809
- `const create = server<typeof Config, ${tc}>(${JSON.stringify(serverOptions)});`
810
- );
811
- async function generateCollectionObject(collection) {
812
- const base = getBase(collection);
813
- switch (collection.type) {
814
- case "docs": {
815
- if (collection.docs.dynamic) return;
816
- if (collection.docs.async) {
817
- const [metaGlob2, headGlob, bodyGlob] = await Promise.all([
818
- generateMetaCollectionGlob(ctx, collection.meta, true),
819
- generateDocCollectionFrontmatterGlob(ctx, collection.docs, true),
820
- generateDocCollectionGlob(ctx, collection.docs)
821
- ]);
822
- return `await create.docsLazy("${collection.name}", "${base}", ${metaGlob2}, ${headGlob}, ${bodyGlob})`;
823
- }
824
- const [metaGlob, docGlob] = await Promise.all([
825
- generateMetaCollectionGlob(ctx, collection.meta, true),
826
- generateDocCollectionGlob(ctx, collection.docs, true)
827
- ]);
828
- return `await create.docs("${collection.name}", "${base}", ${metaGlob}, ${docGlob})`;
829
- }
830
- case "doc":
831
- if (collection.dynamic) return;
832
- if (collection.async) {
833
- const [headGlob, bodyGlob] = await Promise.all([
834
- generateDocCollectionFrontmatterGlob(ctx, collection, true),
835
- generateDocCollectionGlob(ctx, collection)
836
- ]);
837
- return `await create.docLazy("${collection.name}", "${base}", ${headGlob}, ${bodyGlob})`;
838
- }
839
- return `await create.doc("${collection.name}", "${base}", ${await generateDocCollectionGlob(
840
- ctx,
841
- collection,
842
- true
843
- )})`;
844
- case "meta":
845
- return `await create.meta("${collection.name}", "${base}", ${await generateMetaCollectionGlob(
846
- ctx,
847
- collection,
848
- true
849
- )})`;
850
- }
851
- }
852
- await codegen.pushAsync(
853
- core.getCollections().map(async (collection) => {
854
- const obj = await generateCollectionObject(collection);
855
- if (!obj) return;
856
- return `
857
- export const ${collection.name} = ${obj};`;
858
- })
859
- );
664
+ const { core, codegen, serverOptions, tc } = ctx;
665
+ codegen.lines.push(`import { server } from 'fumadocs-mdx/runtime/server';`, `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`, "", `const create = server<typeof Config, ${tc}>(${JSON.stringify(serverOptions)});`);
666
+ async function generateCollectionObject(collection) {
667
+ const base = getBase(collection);
668
+ switch (collection.type) {
669
+ case "docs": {
670
+ if (collection.docs.dynamic) return;
671
+ if (collection.docs.async) {
672
+ const [metaGlob$1, headGlob, bodyGlob] = await Promise.all([
673
+ generateMetaCollectionGlob(ctx, collection.meta, true),
674
+ generateDocCollectionFrontmatterGlob(ctx, collection.docs, true),
675
+ generateDocCollectionGlob(ctx, collection.docs)
676
+ ]);
677
+ return `await create.docsLazy("${collection.name}", "${base}", ${metaGlob$1}, ${headGlob}, ${bodyGlob})`;
678
+ }
679
+ const [metaGlob, docGlob] = await Promise.all([generateMetaCollectionGlob(ctx, collection.meta, true), generateDocCollectionGlob(ctx, collection.docs, true)]);
680
+ return `await create.docs("${collection.name}", "${base}", ${metaGlob}, ${docGlob})`;
681
+ }
682
+ case "doc":
683
+ if (collection.dynamic) return;
684
+ if (collection.async) {
685
+ const [headGlob, bodyGlob] = await Promise.all([generateDocCollectionFrontmatterGlob(ctx, collection, true), generateDocCollectionGlob(ctx, collection)]);
686
+ return `await create.docLazy("${collection.name}", "${base}", ${headGlob}, ${bodyGlob})`;
687
+ }
688
+ return `await create.doc("${collection.name}", "${base}", ${await generateDocCollectionGlob(ctx, collection, true)})`;
689
+ case "meta": return `await create.meta("${collection.name}", "${base}", ${await generateMetaCollectionGlob(ctx, collection, true)})`;
690
+ }
691
+ }
692
+ await codegen.pushAsync(core.getCollections().map(async (collection) => {
693
+ const obj = await generateCollectionObject(collection);
694
+ if (!obj) return;
695
+ return `\nexport const ${collection.name} = ${obj};`;
696
+ }));
860
697
  }
861
698
  async function generateDynamicIndexFile(ctx) {
862
- const { core, codegen, serverOptions, tc } = ctx;
863
- const { configPath, environment, outDir } = core.getOptions();
864
- const partialOptions = {
865
- configPath,
866
- environment,
867
- outDir
868
- };
869
- codegen.lines.push(
870
- `import { dynamic } from 'fumadocs-mdx/runtime/dynamic';`,
871
- `import * as Config from '${codegen.formatImportPath(configPath)}';`,
872
- "",
873
- `const create = await dynamic<typeof Config, ${tc}>(Config, ${JSON.stringify(partialOptions)}, ${JSON.stringify(serverOptions)});`
874
- );
875
- async function generateCollectionObjectEntry(collection, absolutePath) {
876
- const fullPath = import_path.default.relative(process.cwd(), absolutePath);
877
- const content = await indexFileCache.read(fullPath).catch(() => "");
878
- const parsed = fumaMatter(content);
879
- const data = await core.transformFrontmatter(
880
- {
881
- collection,
882
- filePath: fullPath,
883
- source: content
884
- },
885
- parsed.data
886
- );
887
- const hash = (0, import_crypto.createHash)("md5").update(content).digest("hex");
888
- const infoStr = [
889
- // make sure it's included in vercel/nft
890
- `absolutePath: path.resolve(${JSON.stringify(fullPath)})`
891
- ];
892
- for (const [k, v] of Object.entries({
893
- info: {
894
- fullPath,
895
- path: import_path.default.relative(collection.dir, absolutePath)
896
- },
897
- data,
898
- hash
899
- })) {
900
- infoStr.push(`${k}: ${JSON.stringify(v)}`);
901
- }
902
- return `{ ${infoStr.join(", ")} }`;
903
- }
904
- async function generateCollectionObject(parent) {
905
- let collection;
906
- if (parent.type === "doc") collection = parent;
907
- else if (parent.type === "docs") collection = parent.docs;
908
- if (!collection || !collection.dynamic) return;
909
- const files = await (0, import_tinyglobby2.glob)(collection.patterns, {
910
- cwd: collection.dir,
911
- absolute: true
912
- });
913
- const entries = await Promise.all(
914
- files.map((file) => generateCollectionObjectEntry(collection, file))
915
- );
916
- switch (parent.type) {
917
- case "docs": {
918
- const metaGlob = await generateMetaCollectionGlob(
919
- ctx,
920
- parent.meta,
921
- true
922
- );
923
- return `await create.docs("${parent.name}", "${getBase(parent)}", ${metaGlob}, ${entries.join(", ")})`;
924
- }
925
- case "doc":
926
- return `await create.doc("${collection.name}", "${getBase(collection)}", ${entries.join(", ")})`;
927
- }
928
- }
929
- await codegen.pushAsync(
930
- core.getCollections().map(async (collection) => {
931
- const obj = await generateCollectionObject(collection);
932
- if (!obj) return;
933
- return `
934
- export const ${collection.name} = ${obj};`;
935
- })
936
- );
699
+ const { core, codegen, serverOptions, tc } = ctx;
700
+ const { configPath, environment, outDir } = core.getOptions();
701
+ const partialOptions = {
702
+ configPath,
703
+ environment,
704
+ outDir
705
+ };
706
+ codegen.lines.push(`import { dynamic } from 'fumadocs-mdx/runtime/dynamic';`, `import * as Config from '${codegen.formatImportPath(configPath)}';`, "", `const create = await dynamic<typeof Config, ${tc}>(Config, ${JSON.stringify(partialOptions)}, ${JSON.stringify(serverOptions)});`);
707
+ async function generateCollectionObjectEntry(collection, absolutePath) {
708
+ const fullPath = path.default.relative(process.cwd(), absolutePath);
709
+ const content = await indexFileCache.read(fullPath).catch(() => "");
710
+ const parsed = fumaMatter(content);
711
+ const data = await core.transformFrontmatter({
712
+ collection,
713
+ filePath: fullPath,
714
+ source: content
715
+ }, parsed.data);
716
+ const hash = (0, crypto.createHash)("md5").update(content).digest("hex");
717
+ const infoStr = [`absolutePath: path.resolve(${JSON.stringify(fullPath)})`];
718
+ for (const [k, v] of Object.entries({
719
+ info: {
720
+ fullPath,
721
+ path: path.default.relative(collection.dir, absolutePath)
722
+ },
723
+ data,
724
+ hash
725
+ })) infoStr.push(`${k}: ${JSON.stringify(v)}`);
726
+ return `{ ${infoStr.join(", ")} }`;
727
+ }
728
+ async function generateCollectionObject(parent) {
729
+ let collection;
730
+ if (parent.type === "doc") collection = parent;
731
+ else if (parent.type === "docs") collection = parent.docs;
732
+ if (!collection || !collection.dynamic) return;
733
+ const files = await (0, tinyglobby.glob)(collection.patterns, {
734
+ cwd: collection.dir,
735
+ absolute: true
736
+ });
737
+ const entries = await Promise.all(files.map((file) => generateCollectionObjectEntry(collection, file)));
738
+ switch (parent.type) {
739
+ case "docs": {
740
+ const metaGlob = await generateMetaCollectionGlob(ctx, parent.meta, true);
741
+ return `await create.docs("${parent.name}", "${getBase(parent)}", ${metaGlob}, ${entries.join(", ")})`;
742
+ }
743
+ case "doc": return `await create.doc("${collection.name}", "${getBase(collection)}", ${entries.join(", ")})`;
744
+ }
745
+ }
746
+ await codegen.pushAsync(core.getCollections().map(async (collection) => {
747
+ const obj = await generateCollectionObject(collection);
748
+ if (!obj) return;
749
+ return `\nexport const ${collection.name} = ${obj};`;
750
+ }));
937
751
  }
938
752
  async function generateBrowserIndexFile(ctx) {
939
- const { core, codegen, tc } = ctx;
940
- codegen.lines.push(
941
- `import { browser } from 'fumadocs-mdx/runtime/browser';`,
942
- `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`,
943
- "",
944
- `const create = browser<typeof Config, ${tc}>();`
945
- );
946
- async function generateCollectionObject(collection) {
947
- switch (collection.type) {
948
- case "docs": {
949
- if (collection.docs.dynamic) return;
950
- return generateCollectionObject(collection.docs);
951
- }
952
- case "doc":
953
- if (collection.dynamic) return;
954
- return `create.doc("${collection.name}", ${await generateDocCollectionGlob(ctx, collection)})`;
955
- }
956
- }
957
- codegen.lines.push("const browserCollections = {");
958
- await codegen.pushAsync(
959
- core.getCollections().map(async (collection) => {
960
- const obj = await generateCollectionObject(collection);
961
- if (!obj) return;
962
- return ident(`${collection.name}: ${obj},`);
963
- })
964
- );
965
- codegen.lines.push("};", "export default browserCollections;");
753
+ const { core, codegen, tc } = ctx;
754
+ codegen.lines.push(`import { browser } from 'fumadocs-mdx/runtime/browser';`, `import type * as Config from '${codegen.formatImportPath(core.getOptions().configPath)}';`, "", `const create = browser<typeof Config, ${tc}>();`);
755
+ async function generateCollectionObject(collection) {
756
+ switch (collection.type) {
757
+ case "docs":
758
+ if (collection.docs.dynamic) return;
759
+ return generateCollectionObject(collection.docs);
760
+ case "doc":
761
+ if (collection.dynamic) return;
762
+ return `create.doc("${collection.name}", ${await generateDocCollectionGlob(ctx, collection)})`;
763
+ }
764
+ }
765
+ codegen.lines.push("const browserCollections = {");
766
+ await codegen.pushAsync(core.getCollections().map(async (collection) => {
767
+ const obj = await generateCollectionObject(collection);
768
+ if (!obj) return;
769
+ return ident(`${collection.name}: ${obj},`);
770
+ }));
771
+ codegen.lines.push("};", "export default browserCollections;");
966
772
  }
967
773
  function getBase(collection) {
968
- return slash(import_path.default.relative(process.cwd(), collection.dir));
774
+ return slash(path.default.relative(process.cwd(), collection.dir));
969
775
  }
970
776
  function generateDocCollectionFrontmatterGlob({ codegen, workspace }, collection, eager = false) {
971
- return codegen.generateGlobImport(collection.patterns, {
972
- query: {
973
- collection: collection.name,
974
- only: "frontmatter",
975
- workspace
976
- },
977
- import: "frontmatter",
978
- base: collection.dir,
979
- eager
980
- });
777
+ return codegen.generateGlobImport(collection.patterns, {
778
+ query: {
779
+ collection: collection.name,
780
+ only: "frontmatter",
781
+ workspace
782
+ },
783
+ import: "frontmatter",
784
+ base: collection.dir,
785
+ eager
786
+ });
981
787
  }
982
788
  function generateDocCollectionGlob({ codegen, workspace }, collection, eager = false) {
983
- return codegen.generateGlobImport(collection.patterns, {
984
- query: {
985
- collection: collection.name,
986
- workspace
987
- },
988
- base: collection.dir,
989
- eager
990
- });
789
+ return codegen.generateGlobImport(collection.patterns, {
790
+ query: {
791
+ collection: collection.name,
792
+ workspace
793
+ },
794
+ base: collection.dir,
795
+ eager
796
+ });
991
797
  }
992
798
  function generateMetaCollectionGlob({ codegen, workspace }, collection, eager = false) {
993
- return codegen.generateGlobImport(collection.patterns, {
994
- query: {
995
- collection: collection.name,
996
- workspace
997
- },
998
- import: "default",
999
- base: collection.dir,
1000
- eager
1001
- });
799
+ return codegen.generateGlobImport(collection.patterns, {
800
+ query: {
801
+ collection: collection.name,
802
+ workspace
803
+ },
804
+ import: "default",
805
+ base: collection.dir,
806
+ eager
807
+ });
1002
808
  }
1003
809
 
1004
- // src/next/index.ts
1005
- var defaultPageExtensions = ["mdx", "md", "jsx", "js", "tsx", "ts"];
810
+ //#endregion
811
+ //#region src/next/index.ts
812
+ const defaultPageExtensions = [
813
+ "mdx",
814
+ "md",
815
+ "jsx",
816
+ "js",
817
+ "tsx",
818
+ "ts"
819
+ ];
1006
820
  function createMDX(createOptions = {}) {
1007
- const core = createNextCore(applyDefaults(createOptions));
1008
- const isDev = process.env.NODE_ENV === "development";
1009
- if (process.env._FUMADOCS_MDX !== "1") {
1010
- process.env._FUMADOCS_MDX = "1";
1011
- void init(isDev, core);
1012
- }
1013
- return (nextConfig = {}) => {
1014
- const { configPath, outDir } = core.getOptions();
1015
- const loaderOptions = {
1016
- configPath,
1017
- outDir,
1018
- absoluteCompiledConfigPath: path6.resolve(core.getCompiledConfigPath()),
1019
- isDev
1020
- };
1021
- const turbopack = {
1022
- ...nextConfig.turbopack,
1023
- rules: {
1024
- ...nextConfig.turbopack?.rules,
1025
- "*.{md,mdx}": {
1026
- loaders: [
1027
- {
1028
- loader: "fumadocs-mdx/loader-mdx",
1029
- options: loaderOptions
1030
- }
1031
- ],
1032
- as: "*.js"
1033
- },
1034
- "*.json": {
1035
- loaders: [
1036
- {
1037
- loader: "fumadocs-mdx/loader-meta",
1038
- options: loaderOptions
1039
- }
1040
- ],
1041
- as: "*.json"
1042
- },
1043
- "*.yaml": {
1044
- loaders: [
1045
- {
1046
- loader: "fumadocs-mdx/loader-meta",
1047
- options: loaderOptions
1048
- }
1049
- ],
1050
- as: "*.js"
1051
- }
1052
- }
1053
- };
1054
- return {
1055
- ...nextConfig,
1056
- turbopack,
1057
- pageExtensions: nextConfig.pageExtensions ?? defaultPageExtensions,
1058
- webpack: (config, options) => {
1059
- config.resolve ||= {};
1060
- config.module ||= {};
1061
- config.module.rules ||= [];
1062
- config.module.rules.push(
1063
- {
1064
- test: mdxLoaderGlob,
1065
- use: [
1066
- options.defaultLoaders.babel,
1067
- {
1068
- loader: "fumadocs-mdx/loader-mdx",
1069
- options: loaderOptions
1070
- }
1071
- ]
1072
- },
1073
- {
1074
- test: metaLoaderGlob,
1075
- enforce: "pre",
1076
- use: [
1077
- {
1078
- loader: "fumadocs-mdx/loader-meta",
1079
- options: loaderOptions
1080
- }
1081
- ]
1082
- }
1083
- );
1084
- config.plugins ||= [];
1085
- return nextConfig.webpack?.(config, options) ?? config;
1086
- }
1087
- };
1088
- };
821
+ const core = createNextCore(applyDefaults(createOptions));
822
+ const isDev = process.env.NODE_ENV === "development";
823
+ if (process.env._FUMADOCS_MDX !== "1") {
824
+ process.env._FUMADOCS_MDX = "1";
825
+ init(isDev, core);
826
+ }
827
+ return (nextConfig = {}) => {
828
+ const { configPath, outDir } = core.getOptions();
829
+ const loaderOptions = {
830
+ configPath,
831
+ outDir,
832
+ absoluteCompiledConfigPath: node_path.resolve(core.getCompiledConfigPath()),
833
+ isDev
834
+ };
835
+ const turbopack = {
836
+ ...nextConfig.turbopack,
837
+ rules: {
838
+ ...nextConfig.turbopack?.rules,
839
+ "*.{md,mdx}": {
840
+ loaders: [{
841
+ loader: "fumadocs-mdx/loader-mdx",
842
+ options: loaderOptions
843
+ }],
844
+ as: "*.js"
845
+ },
846
+ "*.json": {
847
+ loaders: [{
848
+ loader: "fumadocs-mdx/loader-meta",
849
+ options: loaderOptions
850
+ }],
851
+ as: "*.json"
852
+ },
853
+ "*.yaml": {
854
+ loaders: [{
855
+ loader: "fumadocs-mdx/loader-meta",
856
+ options: loaderOptions
857
+ }],
858
+ as: "*.js"
859
+ }
860
+ }
861
+ };
862
+ return {
863
+ ...nextConfig,
864
+ turbopack,
865
+ pageExtensions: nextConfig.pageExtensions ?? defaultPageExtensions,
866
+ webpack: (config, options) => {
867
+ config.resolve ||= {};
868
+ config.module ||= {};
869
+ config.module.rules ||= [];
870
+ config.module.rules.push({
871
+ test: mdxLoaderGlob,
872
+ use: [options.defaultLoaders.babel, {
873
+ loader: "fumadocs-mdx/loader-mdx",
874
+ options: loaderOptions
875
+ }]
876
+ }, {
877
+ test: metaLoaderGlob,
878
+ enforce: "pre",
879
+ use: [{
880
+ loader: "fumadocs-mdx/loader-meta",
881
+ options: loaderOptions
882
+ }]
883
+ });
884
+ config.plugins ||= [];
885
+ return nextConfig.webpack?.(config, options) ?? config;
886
+ }
887
+ };
888
+ };
1089
889
  }
1090
890
  async function init(dev, core) {
1091
- async function initOrReload() {
1092
- await core.init({
1093
- config: loadConfig(core, true)
1094
- });
1095
- await core.emit({ write: true });
1096
- }
1097
- async function devServer() {
1098
- const { FSWatcher } = await import("chokidar");
1099
- const { configPath, outDir } = core.getOptions();
1100
- const watcher = new FSWatcher({
1101
- ignoreInitial: true,
1102
- persistent: true,
1103
- ignored: [outDir]
1104
- });
1105
- watcher.add(configPath);
1106
- for (const collection of core.getCollections()) {
1107
- watcher.add(collection.dir);
1108
- }
1109
- for (const workspace of core.getWorkspaces().values()) {
1110
- for (const collection of workspace.getCollections()) {
1111
- watcher.add(collection.dir);
1112
- }
1113
- }
1114
- watcher.on("ready", () => {
1115
- console.log("[MDX] started dev server");
1116
- });
1117
- const absoluteConfigPath = path6.resolve(configPath);
1118
- watcher.on("all", async (_event, file) => {
1119
- if (path6.resolve(file) === absoluteConfigPath) {
1120
- watcher.removeAllListeners();
1121
- await watcher.close();
1122
- await initOrReload();
1123
- console.log("[MDX] restarting dev server");
1124
- await devServer();
1125
- }
1126
- });
1127
- process.on("exit", () => {
1128
- if (watcher.closed) return;
1129
- console.log("[MDX] closing dev server");
1130
- void watcher.close();
1131
- });
1132
- await core.initServer({ watcher });
1133
- }
1134
- await initOrReload();
1135
- if (dev) {
1136
- await devServer();
1137
- }
891
+ async function initOrReload() {
892
+ await core.init({ config: loadConfig(core, true) });
893
+ await core.emit({ write: true });
894
+ }
895
+ async function devServer() {
896
+ const { FSWatcher } = await import("chokidar");
897
+ const { configPath, outDir } = core.getOptions();
898
+ const watcher = new FSWatcher({
899
+ ignoreInitial: true,
900
+ persistent: true,
901
+ ignored: [outDir]
902
+ });
903
+ watcher.add(configPath);
904
+ for (const collection of core.getCollections()) watcher.add(collection.dir);
905
+ for (const workspace of core.getWorkspaces().values()) for (const collection of workspace.getCollections()) watcher.add(collection.dir);
906
+ watcher.on("ready", () => {
907
+ console.log("[MDX] started dev server");
908
+ });
909
+ const absoluteConfigPath = node_path.resolve(configPath);
910
+ watcher.on("all", async (_event, file) => {
911
+ if (node_path.resolve(file) === absoluteConfigPath) {
912
+ watcher.removeAllListeners();
913
+ await watcher.close();
914
+ await initOrReload();
915
+ console.log("[MDX] restarting dev server");
916
+ await devServer();
917
+ }
918
+ });
919
+ process.on("exit", () => {
920
+ if (watcher.closed) return;
921
+ console.log("[MDX] closing dev server");
922
+ watcher.close();
923
+ });
924
+ await core.initServer({ watcher });
925
+ }
926
+ await initOrReload();
927
+ if (dev) await devServer();
1138
928
  }
1139
929
  async function postInstall(options) {
1140
- const core = createNextCore(applyDefaults(options));
1141
- await core.init({
1142
- config: loadConfig(core, true)
1143
- });
1144
- await core.emit({ write: true });
930
+ const core = createNextCore(applyDefaults(options));
931
+ await core.init({ config: loadConfig(core, true) });
932
+ await core.emit({ write: true });
1145
933
  }
1146
934
  function applyDefaults(options) {
1147
- return {
1148
- index: {},
1149
- outDir: options.outDir ?? _Defaults.outDir,
1150
- configPath: options.configPath ?? _Defaults.configPath
1151
- };
935
+ return {
936
+ index: {},
937
+ outDir: options.outDir ?? _Defaults.outDir,
938
+ configPath: options.configPath ?? _Defaults.configPath
939
+ };
1152
940
  }
1153
941
  function createNextCore(options) {
1154
- return createCore({
1155
- environment: "next",
1156
- outDir: options.outDir,
1157
- configPath: options.configPath,
1158
- plugins: [options.index && indexFile(options.index)]
1159
- });
942
+ return createCore({
943
+ environment: "next",
944
+ outDir: options.outDir,
945
+ configPath: options.configPath,
946
+ plugins: [options.index && indexFile(options.index)]
947
+ });
1160
948
  }
1161
- // Annotate the CommonJS export names for ESM import in node:
1162
- 0 && (module.exports = {
1163
- createMDX,
1164
- postInstall
1165
- });
949
+
950
+ //#endregion
951
+ exports.createMDX = createMDX;
952
+ exports.postInstall = postInstall;