fumadocs-mdx 14.0.1 → 14.0.2

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 (72) hide show
  1. package/dist/{build-mdx-6UAK5FF5.js → build-mdx-W3233QBZ.js} +1 -1
  2. package/dist/bun/index.d.ts +1 -1
  3. package/dist/bun/index.js +5 -5
  4. package/dist/{chunk-ZY6UZ7NH.js → chunk-6RPNS75C.js} +1 -1
  5. package/dist/{chunk-7UKSZSPY.js → chunk-ED3ON275.js} +3 -4
  6. package/dist/{chunk-BEBCWQC7.js → chunk-GB4W3YCZ.js} +1 -1
  7. package/dist/{chunk-SLY7WXTX.js → chunk-KOPLIEVQ.js} +5 -6
  8. package/dist/{chunk-MTTISKQJ.js → chunk-LPX7ZO66.js} +1 -1
  9. package/dist/{chunk-K6HCOGOX.js → chunk-OLL7FM7W.js} +2 -2
  10. package/dist/{chunk-IQGEFL2B.js → chunk-Q5OSGLJL.js} +1 -1
  11. package/dist/{chunk-E5DJTSIM.js → chunk-S7KOJHHO.js} +4 -1
  12. package/dist/{chunk-6NISOLQ6.js → chunk-USWQVJWR.js} +1 -1
  13. package/dist/config/index.d.ts +1 -1
  14. package/dist/config/index.js +1 -1
  15. package/dist/{core-B9ZoS6sA.d.ts → core-C3QZSdEx.d.ts} +1 -1
  16. package/dist/{index-CNOvhtOn.d.ts → index-RVIZxMZG.d.ts} +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/load-from-file-OZ5N7DXU.js +8 -0
  19. package/dist/next/index.cjs +8 -6
  20. package/dist/next/index.d.ts +1 -1
  21. package/dist/next/index.js +5 -5
  22. package/dist/node/loader.js +3 -3
  23. package/dist/plugins/index-file.d.ts +1 -1
  24. package/dist/plugins/index-file.js +1 -1
  25. package/dist/plugins/json-schema.d.ts +1 -1
  26. package/dist/plugins/last-modified.d.ts +5 -2
  27. package/dist/plugins/last-modified.js +10 -3
  28. package/dist/runtime/browser.d.ts +1 -1
  29. package/dist/runtime/dynamic.d.ts +1 -1
  30. package/dist/runtime/dynamic.js +4 -4
  31. package/dist/runtime/server.d.ts +1 -1
  32. package/dist/vite/index.d.ts +1 -1
  33. package/dist/vite/index.js +7 -7
  34. package/dist/webpack/mdx.d.ts +2 -2
  35. package/dist/webpack/mdx.js +4 -4
  36. package/dist/webpack/meta.d.ts +2 -2
  37. package/dist/webpack/meta.js +3 -3
  38. package/package.json +4 -6
  39. package/dist/bin.cjs +0 -1958
  40. package/dist/bin.d.cts +0 -1
  41. package/dist/bun/index.cjs +0 -1147
  42. package/dist/bun/index.d.cts +0 -25
  43. package/dist/config/index.cjs +0 -400
  44. package/dist/config/index.d.cts +0 -18
  45. package/dist/core-DTuP23zu.d.cts +0 -341
  46. package/dist/index-BD8Woo4m.d.cts +0 -8
  47. package/dist/index.cjs +0 -18
  48. package/dist/index.d.cts +0 -61
  49. package/dist/load-from-file-5HUQN36V.js +0 -8
  50. package/dist/next/index.d.cts +0 -33
  51. package/dist/node/loader.cjs +0 -1200
  52. package/dist/node/loader.d.cts +0 -5
  53. package/dist/plugins/index-file.cjs +0 -495
  54. package/dist/plugins/index-file.d.cts +0 -14
  55. package/dist/plugins/json-schema.cjs +0 -114
  56. package/dist/plugins/json-schema.d.cts +0 -31
  57. package/dist/plugins/last-modified.cjs +0 -110
  58. package/dist/plugins/last-modified.d.cts +0 -37
  59. package/dist/runtime/browser.cjs +0 -93
  60. package/dist/runtime/browser.d.cts +0 -53
  61. package/dist/runtime/dynamic.cjs +0 -1023
  62. package/dist/runtime/dynamic.d.cts +0 -27
  63. package/dist/runtime/server.cjs +0 -176
  64. package/dist/runtime/server.d.cts +0 -14
  65. package/dist/runtime/types.cjs +0 -18
  66. package/dist/runtime/types.d.cts +0 -61
  67. package/dist/vite/index.cjs +0 -1687
  68. package/dist/vite/index.d.cts +0 -44
  69. package/dist/webpack/mdx.cjs +0 -1124
  70. package/dist/webpack/mdx.d.cts +0 -20
  71. package/dist/webpack/meta.cjs +0 -684
  72. package/dist/webpack/meta.d.cts +0 -20
@@ -1,1124 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // src/utils/fuma-matter.ts
34
- function fumaMatter(input) {
35
- const output = { matter: "", data: {}, content: input };
36
- const match = regex.exec(input);
37
- if (!match) {
38
- return output;
39
- }
40
- output.matter = match[0];
41
- output.content = input.slice(match[0].length);
42
- const loaded = (0, import_js_yaml.load)(match[1]);
43
- output.data = loaded ?? {};
44
- return output;
45
- }
46
- var import_js_yaml, regex;
47
- var init_fuma_matter = __esm({
48
- "src/utils/fuma-matter.ts"() {
49
- "use strict";
50
- import_js_yaml = require("js-yaml");
51
- regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
52
- }
53
- });
54
-
55
- // src/loaders/mdx/remark-unravel.ts
56
- function remarkMarkAndUnravel() {
57
- return (tree) => {
58
- (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
59
- let offset = -1;
60
- let all = true;
61
- let oneOrMore = false;
62
- if (parent && typeof index === "number" && node.type === "paragraph") {
63
- const children = node.children;
64
- while (++offset < children.length) {
65
- const child = children[offset];
66
- if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
67
- oneOrMore = true;
68
- } else if (child.type === "text" && child.value.trim().length === 0) {
69
- } else {
70
- all = false;
71
- break;
72
- }
73
- }
74
- if (all && oneOrMore) {
75
- offset = -1;
76
- const newChildren = [];
77
- while (++offset < children.length) {
78
- const child = children[offset];
79
- if (child.type === "mdxJsxTextElement") {
80
- child.type = "mdxJsxFlowElement";
81
- }
82
- if (child.type === "mdxTextExpression") {
83
- child.type = "mdxFlowExpression";
84
- }
85
- if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
86
- } else {
87
- newChildren.push(child);
88
- }
89
- }
90
- parent.children.splice(index, 1, ...newChildren);
91
- return index;
92
- }
93
- }
94
- });
95
- };
96
- }
97
- var import_unist_util_visit;
98
- var init_remark_unravel = __esm({
99
- "src/loaders/mdx/remark-unravel.ts"() {
100
- "use strict";
101
- import_unist_util_visit = require("unist-util-visit");
102
- }
103
- });
104
-
105
- // src/loaders/mdx/mdast-utils.ts
106
- function flattenNode(node) {
107
- if ("children" in node)
108
- return node.children.map((child) => flattenNode(child)).join("");
109
- if ("value" in node) return node.value;
110
- return "";
111
- }
112
- var init_mdast_utils = __esm({
113
- "src/loaders/mdx/mdast-utils.ts"() {
114
- "use strict";
115
- }
116
- });
117
-
118
- // src/loaders/mdx/remark-include.ts
119
- function isElementLike(node) {
120
- return ElementLikeTypes.includes(node.type);
121
- }
122
- function parseElementAttributes(element) {
123
- if (Array.isArray(element.attributes)) {
124
- const attributes = {};
125
- for (const attr of element.attributes) {
126
- if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
127
- attributes[attr.name] = attr.value;
128
- }
129
- }
130
- return attributes;
131
- }
132
- return element.attributes ?? {};
133
- }
134
- function parseSpecifier(specifier) {
135
- const idx = specifier.lastIndexOf("#");
136
- if (idx === -1) return { file: specifier };
137
- return {
138
- file: specifier.slice(0, idx),
139
- section: specifier.slice(idx + 1)
140
- };
141
- }
142
- function extractSection(root, section) {
143
- let nodes;
144
- let capturingHeadingContent = false;
145
- (0, import_unist_util_visit2.visit)(root, (node) => {
146
- if (node.type === "heading") {
147
- if (capturingHeadingContent) {
148
- return false;
149
- }
150
- if (node.data?.hProperties?.id === section) {
151
- capturingHeadingContent = true;
152
- nodes = [node];
153
- return "skip";
154
- }
155
- return;
156
- }
157
- if (capturingHeadingContent) {
158
- nodes?.push(node);
159
- return "skip";
160
- }
161
- if (isElementLike(node) && node.name === "section") {
162
- const attributes = parseElementAttributes(node);
163
- if (attributes.id === section) {
164
- nodes = node.children;
165
- return false;
166
- }
167
- }
168
- });
169
- if (nodes)
170
- return {
171
- type: "root",
172
- children: nodes
173
- };
174
- }
175
- function remarkInclude() {
176
- const TagName = "include";
177
- const embedContent = async (file, heading, params, data) => {
178
- let content;
179
- try {
180
- content = (await fs.readFile(file)).toString();
181
- } catch (e) {
182
- throw new Error(
183
- `failed to read file ${file}
184
- ${e instanceof Error ? e.message : String(e)}`,
185
- { cause: e }
186
- );
187
- }
188
- const ext = path.extname(file);
189
- data._compiler?.addDependency(file);
190
- if (params.lang || ext !== ".md" && ext !== ".mdx") {
191
- const lang = params.lang ?? ext.slice(1);
192
- return {
193
- type: "code",
194
- lang,
195
- meta: params.meta,
196
- value: content,
197
- data: {}
198
- };
199
- }
200
- const parser = data._getProcessor ? data._getProcessor(ext === ".mdx" ? "mdx" : "md") : this;
201
- const parsed = fumaMatter(content);
202
- let mdast = parser.parse({
203
- path: file,
204
- value: parsed.content,
205
- data: { frontmatter: parsed.data }
206
- });
207
- const baseProcessor = (0, import_unified.unified)().use(remarkMarkAndUnravel);
208
- if (heading) {
209
- const extracted = extractSection(
210
- await baseProcessor.use(import_mdx_plugins.remarkHeading).run(mdast),
211
- heading
212
- );
213
- if (!extracted)
214
- throw new Error(
215
- `Cannot find section ${heading} in ${file}, make sure you have encapsulated the section in a <section id="${heading}"> tag, or a :::section directive with remark-directive configured.`
216
- );
217
- mdast = extracted;
218
- } else {
219
- mdast = await baseProcessor.run(mdast);
220
- }
221
- await update(mdast, path.dirname(file), data);
222
- return mdast;
223
- };
224
- async function update(tree, directory, data) {
225
- const queue = [];
226
- (0, import_unist_util_visit2.visit)(tree, ElementLikeTypes, (_node, _, parent) => {
227
- const node = _node;
228
- if (node.name !== TagName) return;
229
- const specifier = flattenNode(node);
230
- if (specifier.length === 0) return "skip";
231
- const attributes = parseElementAttributes(node);
232
- const { file: relativePath, section } = parseSpecifier(specifier);
233
- const file = path.resolve(
234
- "cwd" in attributes ? process.cwd() : directory,
235
- relativePath
236
- );
237
- queue.push(
238
- embedContent(file, section, attributes, data).then((replace) => {
239
- Object.assign(
240
- parent && parent.type === "paragraph" ? parent : node,
241
- replace
242
- );
243
- })
244
- );
245
- return "skip";
246
- });
247
- await Promise.all(queue);
248
- }
249
- return async (tree, file) => {
250
- await update(tree, path.dirname(file.path), file.data);
251
- };
252
- }
253
- var import_unified, import_unist_util_visit2, path, fs, import_mdx_plugins, ElementLikeTypes;
254
- var init_remark_include = __esm({
255
- "src/loaders/mdx/remark-include.ts"() {
256
- "use strict";
257
- import_unified = require("unified");
258
- import_unist_util_visit2 = require("unist-util-visit");
259
- path = __toESM(require("path"), 1);
260
- fs = __toESM(require("fs/promises"), 1);
261
- init_fuma_matter();
262
- import_mdx_plugins = require("fumadocs-core/mdx-plugins");
263
- init_remark_unravel();
264
- init_mdast_utils();
265
- ElementLikeTypes = [
266
- "mdxJsxFlowElement",
267
- "mdxJsxTextElement",
268
- "containerDirective",
269
- "textDirective",
270
- "leafDirective"
271
- ];
272
- }
273
- });
274
-
275
- // src/loaders/mdx/remark-postprocess.ts
276
- function remarkPostprocess({
277
- _format,
278
- includeProcessedMarkdown = false,
279
- includeMDAST = false,
280
- extractLinkReferences = false,
281
- valueToExport = []
282
- }) {
283
- let _stringifyProcessor;
284
- const getStringifyProcessor = () => {
285
- return _stringifyProcessor ??= _format === "mdx" ? this : (
286
- // force Markdown processor to stringify MDX nodes
287
- this().use(import_remark_mdx.default).freeze()
288
- );
289
- };
290
- return (tree, file) => {
291
- const frontmatter = file.data.frontmatter ??= {};
292
- if (!frontmatter.title) {
293
- (0, import_unist_util_visit3.visit)(tree, "heading", (node) => {
294
- if (node.depth === 1) {
295
- frontmatter.title = flattenNode(node);
296
- return false;
297
- }
298
- });
299
- }
300
- file.data["mdx-export"] ??= [];
301
- if (extractLinkReferences) {
302
- const urls = [];
303
- (0, import_unist_util_visit3.visit)(tree, "link", (node) => {
304
- urls.push({
305
- href: node.url
306
- });
307
- return "skip";
308
- });
309
- file.data["mdx-export"].push({
310
- name: "extractedReferences",
311
- value: urls
312
- });
313
- }
314
- if (includeProcessedMarkdown) {
315
- const processor = getStringifyProcessor();
316
- const markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
317
- ...processor.data("settings"),
318
- // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
319
- extensions: processor.data("toMarkdownExtensions") || []
320
- });
321
- file.data["mdx-export"].push({
322
- name: "_markdown",
323
- value: markdown
324
- });
325
- }
326
- if (includeMDAST) {
327
- const options = includeMDAST === true ? {} : includeMDAST;
328
- const mdast = JSON.stringify(
329
- options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
330
- );
331
- file.data["mdx-export"].push({
332
- name: "_mdast",
333
- value: mdast
334
- });
335
- }
336
- for (const { name, value } of file.data["mdx-export"]) {
337
- tree.children.unshift(getMdastExport(name, value));
338
- }
339
- file.data["mdx-export"] = [];
340
- for (const name of valueToExport) {
341
- if (!(name in file.data)) continue;
342
- tree.children.unshift(getMdastExport(name, file.data[name]));
343
- }
344
- };
345
- }
346
- function getMdastExport(name, value) {
347
- return {
348
- type: "mdxjsEsm",
349
- value: "",
350
- data: {
351
- estree: {
352
- type: "Program",
353
- sourceType: "module",
354
- body: [
355
- {
356
- type: "ExportNamedDeclaration",
357
- attributes: [],
358
- specifiers: [],
359
- source: null,
360
- declaration: {
361
- type: "VariableDeclaration",
362
- kind: "let",
363
- declarations: [
364
- {
365
- type: "VariableDeclarator",
366
- id: {
367
- type: "Identifier",
368
- name
369
- },
370
- init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
371
- }
372
- ]
373
- }
374
- }
375
- ]
376
- }
377
- }
378
- };
379
- }
380
- var import_unist_util_visit3, import_mdast_util_to_markdown, import_estree_util_value_to_estree, import_unist_util_remove_position, import_remark_mdx;
381
- var init_remark_postprocess = __esm({
382
- "src/loaders/mdx/remark-postprocess.ts"() {
383
- "use strict";
384
- import_unist_util_visit3 = require("unist-util-visit");
385
- import_mdast_util_to_markdown = require("mdast-util-to-markdown");
386
- import_estree_util_value_to_estree = require("estree-util-value-to-estree");
387
- import_unist_util_remove_position = require("unist-util-remove-position");
388
- import_remark_mdx = __toESM(require("remark-mdx"), 1);
389
- init_mdast_utils();
390
- }
391
- });
392
-
393
- // src/loaders/mdx/build-mdx.ts
394
- var build_mdx_exports = {};
395
- __export(build_mdx_exports, {
396
- buildMDX: () => buildMDX
397
- });
398
- async function buildMDX(core2, collection, {
399
- filePath,
400
- frontmatter,
401
- source,
402
- _compiler,
403
- environment,
404
- isDevelopment
405
- }) {
406
- const mdxOptions = await core2.getConfig().getMDXOptions(collection, environment);
407
- function getProcessor(format) {
408
- const cache = core2.cache;
409
- const key = `build-mdx:${collection?.name ?? "global"}:${format}`;
410
- let processor = cache.get(key);
411
- if (!processor) {
412
- const postprocessOptions = {
413
- _format: format,
414
- ...collection?.postprocess,
415
- valueToExport: [
416
- ...collection?.postprocess?.valueToExport ?? [],
417
- "structuredData",
418
- "frontmatter"
419
- ]
420
- };
421
- processor = (0, import_mdx.createProcessor)({
422
- outputFormat: "program",
423
- development: isDevelopment,
424
- ...mdxOptions,
425
- remarkPlugins: [
426
- remarkInclude,
427
- ...mdxOptions.remarkPlugins ?? [],
428
- [remarkPostprocess, postprocessOptions]
429
- ],
430
- format
431
- });
432
- cache.set(key, processor);
433
- }
434
- return processor;
435
- }
436
- let vfile = new import_vfile.VFile({
437
- value: source,
438
- path: filePath,
439
- data: { frontmatter, _compiler, _getProcessor: getProcessor }
440
- });
441
- if (collection) {
442
- vfile = await core2.transformVFile({ collection, filePath, source }, vfile);
443
- }
444
- return getProcessor(filePath.endsWith(".mdx") ? "mdx" : "md").process(vfile);
445
- }
446
- var import_mdx, import_vfile;
447
- var init_build_mdx = __esm({
448
- "src/loaders/mdx/build-mdx.ts"() {
449
- "use strict";
450
- import_mdx = require("@mdx-js/mdx");
451
- import_vfile = require("vfile");
452
- init_remark_include();
453
- init_remark_postprocess();
454
- }
455
- });
456
-
457
- // src/config/preset.ts
458
- function pluginOption(def, options = []) {
459
- const list = def(Array.isArray(options) ? options : []).filter(
460
- Boolean
461
- );
462
- if (typeof options === "function") {
463
- return options(list);
464
- }
465
- return list;
466
- }
467
- function applyMdxPreset(options = {}) {
468
- return async (environment = "bundler") => {
469
- if (options.preset === "minimal") return options;
470
- const plugins = await import("fumadocs-core/mdx-plugins");
471
- const {
472
- valueToExport = [],
473
- rehypeCodeOptions,
474
- remarkImageOptions,
475
- remarkHeadingOptions,
476
- remarkStructureOptions,
477
- remarkCodeTabOptions,
478
- remarkNpmOptions,
479
- ...mdxOptions
480
- } = options;
481
- const remarkPlugins = pluginOption(
482
- (v) => [
483
- plugins.remarkGfm,
484
- [
485
- plugins.remarkHeading,
486
- {
487
- generateToc: false,
488
- ...remarkHeadingOptions
489
- }
490
- ],
491
- remarkImageOptions !== false && [
492
- plugins.remarkImage,
493
- {
494
- ...remarkImageOptions,
495
- useImport: remarkImageOptions?.useImport ?? environment === "bundler"
496
- }
497
- ],
498
- "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
499
- plugins.remarkCodeTab,
500
- remarkCodeTabOptions
501
- ],
502
- "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
503
- ...v,
504
- remarkStructureOptions !== false && [
505
- plugins.remarkStructure,
506
- remarkStructureOptions
507
- ],
508
- valueToExport.length > 0 && (() => {
509
- return (_, file) => {
510
- file.data["mdx-export"] ??= [];
511
- for (const name of valueToExport) {
512
- if (!(name in file.data)) continue;
513
- file.data["mdx-export"].push({
514
- name,
515
- value: file.data[name]
516
- });
517
- }
518
- };
519
- })
520
- ],
521
- mdxOptions.remarkPlugins
522
- );
523
- const rehypePlugins = pluginOption(
524
- (v) => [
525
- rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
526
- ...v,
527
- plugins.rehypeToc
528
- ],
529
- mdxOptions.rehypePlugins
530
- );
531
- return {
532
- ...mdxOptions,
533
- outputFormat: environment === "runtime" ? "function-body" : mdxOptions.outputFormat,
534
- remarkPlugins,
535
- rehypePlugins
536
- };
537
- };
538
- }
539
- var init_preset = __esm({
540
- "src/config/preset.ts"() {
541
- "use strict";
542
- }
543
- });
544
-
545
- // src/config/build.ts
546
- function buildCollection(name, config) {
547
- if (config.type === "docs") {
548
- return {
549
- ...config,
550
- name,
551
- meta: buildPrimitiveCollection(name, config.meta),
552
- docs: buildPrimitiveCollection(name, config.docs),
553
- hasFile(filePath) {
554
- return this.docs.hasFile(filePath) || this.meta.hasFile(filePath);
555
- }
556
- };
557
- }
558
- return buildPrimitiveCollection(name, config);
559
- }
560
- function buildPrimitiveCollection(name, { files, ...config }) {
561
- const supportedFormats = SupportedFormats[config.type];
562
- const patterns = files ?? [`**/*.{${supportedFormats.join(",")}}`];
563
- let matchers;
564
- return {
565
- ...config,
566
- name,
567
- patterns,
568
- isFileSupported(filePath) {
569
- return supportedFormats.some((format) => filePath.endsWith(`.${format}`));
570
- },
571
- hasFile(filePath) {
572
- matchers ??= (Array.isArray(config.dir) ? config.dir : [config.dir]).map(
573
- (dir) => (0, import_picomatch.default)(patterns, {
574
- cwd: dir
575
- })
576
- );
577
- return this.isFileSupported(filePath) && matchers.some((matcher) => matcher(filePath));
578
- }
579
- };
580
- }
581
- function buildConfig(config) {
582
- const collections = /* @__PURE__ */ new Map();
583
- const loaded = {};
584
- for (const [k, v] of Object.entries(config)) {
585
- if (!v) {
586
- continue;
587
- }
588
- if (typeof v === "object" && "type" in v) {
589
- if (v.type === "docs") {
590
- collections.set(k, buildCollection(k, v));
591
- continue;
592
- }
593
- if (v.type === "doc" || v.type === "meta") {
594
- collections.set(
595
- k,
596
- buildCollection(k, v)
597
- );
598
- continue;
599
- }
600
- }
601
- if (k === "default" && v) {
602
- Object.assign(loaded, v);
603
- continue;
604
- }
605
- throw new Error(
606
- `Unknown export "${k}", you can only export collections from source configuration file.`
607
- );
608
- }
609
- const mdxOptionsCache = /* @__PURE__ */ new Map();
610
- return {
611
- global: loaded,
612
- collectionList: Array.from(collections.values()),
613
- getCollection(name) {
614
- return collections.get(name);
615
- },
616
- getMDXOptions(collection, environment = "bundler") {
617
- const key = collection ? `${environment}:${collection.name}` : environment;
618
- const cached = mdxOptionsCache.get(key);
619
- if (cached) return cached;
620
- let result;
621
- if (collection?.mdxOptions) {
622
- const optionsFn = collection.mdxOptions;
623
- result = typeof optionsFn === "function" ? optionsFn(environment) : optionsFn;
624
- } else {
625
- result = (async () => {
626
- const optionsFn = this.global.mdxOptions;
627
- const options = typeof optionsFn === "function" ? await optionsFn() : optionsFn;
628
- return applyMdxPreset(options)(environment);
629
- })();
630
- }
631
- mdxOptionsCache.set(key, result);
632
- return result;
633
- }
634
- };
635
- }
636
- var import_picomatch, SupportedFormats;
637
- var init_build = __esm({
638
- "src/config/build.ts"() {
639
- "use strict";
640
- import_picomatch = __toESM(require("picomatch"), 1);
641
- init_preset();
642
- SupportedFormats = {
643
- doc: ["mdx", "md"],
644
- meta: ["json", "yaml"]
645
- };
646
- }
647
- });
648
-
649
- // src/config/load-from-file.ts
650
- var load_from_file_exports = {};
651
- __export(load_from_file_exports, {
652
- loadConfig: () => loadConfig
653
- });
654
- async function compileConfig(core2) {
655
- const { build } = await import("esbuild");
656
- const { configPath, outDir } = core2.getOptions();
657
- const transformed = await build({
658
- entryPoints: [{ in: configPath, out: "source.config" }],
659
- bundle: true,
660
- outdir: outDir,
661
- target: "node20",
662
- write: true,
663
- platform: "node",
664
- format: "esm",
665
- packages: "external",
666
- outExtension: {
667
- ".js": ".mjs"
668
- },
669
- allowOverwrite: true
670
- });
671
- if (transformed.errors.length > 0) {
672
- throw new Error("failed to compile configuration file");
673
- }
674
- }
675
- async function loadConfig(core2, build = false) {
676
- if (build) await compileConfig(core2);
677
- const url = (0, import_node_url2.pathToFileURL)(core2.getCompiledConfigPath());
678
- url.searchParams.set("hash", Date.now().toString());
679
- const config = import(url.href).then(
680
- (loaded) => buildConfig(loaded)
681
- );
682
- return await config;
683
- }
684
- var import_node_url2;
685
- var init_load_from_file = __esm({
686
- "src/config/load-from-file.ts"() {
687
- "use strict";
688
- import_node_url2 = require("url");
689
- init_build();
690
- }
691
- });
692
-
693
- // src/webpack/mdx.ts
694
- var mdx_exports = {};
695
- __export(mdx_exports, {
696
- default: () => loader
697
- });
698
- module.exports = __toCommonJS(mdx_exports);
699
-
700
- // src/loaders/mdx/index.ts
701
- init_fuma_matter();
702
- var import_zod = require("zod");
703
- var import_promises = __toESM(require("fs/promises"), 1);
704
- var import_node_path = __toESM(require("path"), 1);
705
- var import_node_crypto = require("crypto");
706
-
707
- // src/loaders/index.ts
708
- var mdxLoaderGlob = /\.mdx?(\?.+?)?$/;
709
-
710
- // src/loaders/mdx/index.ts
711
- var querySchema = import_zod.z.object({
712
- only: import_zod.z.literal(["frontmatter", "all"]).default("all"),
713
- collection: import_zod.z.string().optional()
714
- }).loose();
715
- var cacheEntry = import_zod.z.object({
716
- code: import_zod.z.string(),
717
- map: import_zod.z.any().optional(),
718
- hash: import_zod.z.string().optional()
719
- });
720
- function createMdxLoader(configLoader) {
721
- return {
722
- test: mdxLoaderGlob,
723
- async load({
724
- getSource,
725
- development: isDevelopment,
726
- query,
727
- compiler,
728
- filePath
729
- }) {
730
- const config = await configLoader.getConfig();
731
- const value = await getSource();
732
- const matter = fumaMatter(value);
733
- const parsed = querySchema.parse(query);
734
- let after;
735
- if (!isDevelopment && config.global.experimentalBuildCache) {
736
- const cacheDir = config.global.experimentalBuildCache;
737
- const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
738
- const cached = await import_promises.default.readFile(import_node_path.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
739
- if (cached && cached.hash === generateCacheHash(value)) return cached;
740
- after = async () => {
741
- await import_promises.default.mkdir(cacheDir, { recursive: true });
742
- await import_promises.default.writeFile(
743
- import_node_path.default.join(cacheDir, cacheKey),
744
- JSON.stringify({
745
- ...out,
746
- hash: generateCacheHash(value)
747
- })
748
- );
749
- };
750
- }
751
- const collection = parsed.collection ? config.getCollection(parsed.collection) : void 0;
752
- let docCollection;
753
- switch (collection?.type) {
754
- case "doc":
755
- docCollection = collection;
756
- break;
757
- case "docs":
758
- docCollection = collection.docs;
759
- break;
760
- }
761
- if (docCollection) {
762
- matter.data = await configLoader.core.transformFrontmatter(
763
- { collection: docCollection, filePath, source: value },
764
- matter.data
765
- );
766
- }
767
- if (parsed.only === "frontmatter") {
768
- return {
769
- code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
770
- map: null
771
- };
772
- }
773
- const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
774
- const { buildMDX: buildMDX2 } = await Promise.resolve().then(() => (init_build_mdx(), build_mdx_exports));
775
- const compiled = await buildMDX2(configLoader.core, docCollection, {
776
- isDevelopment,
777
- source: "\n".repeat(lineOffset) + matter.content,
778
- filePath,
779
- frontmatter: matter.data,
780
- _compiler: compiler,
781
- environment: "bundler"
782
- });
783
- const out = {
784
- code: String(compiled.value),
785
- map: compiled.map
786
- };
787
- await after?.();
788
- return out;
789
- }
790
- };
791
- }
792
- function generateCacheHash(input) {
793
- return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
794
- }
795
- function countLines(s) {
796
- let num = 0;
797
- for (const c of s) {
798
- if (c === "\n") num++;
799
- }
800
- return num;
801
- }
802
-
803
- // src/loaders/adapter.ts
804
- var import_node_url = require("url");
805
- var import_promises2 = __toESM(require("fs/promises"), 1);
806
- var import_node_querystring = require("querystring");
807
-
808
- // src/utils/validation.ts
809
- var ValidationError = class extends Error {
810
- constructor(message, issues) {
811
- super(
812
- `${message}:
813
- ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
814
- );
815
- this.title = message;
816
- this.issues = issues;
817
- }
818
- async toStringFormatted() {
819
- const picocolors = await import("picocolors");
820
- return [
821
- picocolors.bold(`[MDX] ${this.title}:`),
822
- ...this.issues.map(
823
- (issue) => picocolors.redBright(
824
- `- ${picocolors.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
825
- )
826
- )
827
- ].join("\n");
828
- }
829
- };
830
- async function validate(schema, data, context, errorMessage) {
831
- if (typeof schema === "function" && !("~standard" in schema)) {
832
- schema = schema(context);
833
- }
834
- if ("~standard" in schema) {
835
- const result = await schema["~standard"].validate(
836
- data
837
- );
838
- if (result.issues) {
839
- throw new ValidationError(errorMessage, result.issues);
840
- }
841
- return result.value;
842
- }
843
- return data;
844
- }
845
-
846
- // src/loaders/adapter.ts
847
- var import_node_path2 = __toESM(require("path"), 1);
848
- var import_node_fs = require("fs");
849
- function toWebpack(loader2) {
850
- return async function(source, callback) {
851
- try {
852
- const result = await loader2.load({
853
- filePath: this.resourcePath,
854
- query: (0, import_node_querystring.parse)(this.resourceQuery.slice(1)),
855
- getSource() {
856
- return source;
857
- },
858
- development: this.mode === "development",
859
- compiler: this
860
- });
861
- if (result === null) {
862
- callback(void 0, source);
863
- } else {
864
- callback(void 0, result.code, result.map);
865
- }
866
- } catch (error) {
867
- if (error instanceof ValidationError) {
868
- return callback(new Error(await error.toStringFormatted()));
869
- }
870
- if (!(error instanceof Error)) throw error;
871
- const fpath = import_node_path2.default.relative(this.context, this.resourcePath);
872
- error.message = `${fpath}:${error.name}: ${error.message}`;
873
- callback(error);
874
- }
875
- };
876
- }
877
-
878
- // src/loaders/config.ts
879
- var import_promises3 = __toESM(require("fs/promises"), 1);
880
- function createStandaloneConfigLoader({
881
- core: core2,
882
- buildConfig: buildConfig2,
883
- mode
884
- }) {
885
- let loaded;
886
- async function getConfigHash() {
887
- if (mode === "production") return "static";
888
- const stats = await import_promises3.default.stat(core2.getOptions().configPath).catch(() => {
889
- throw new Error("Cannot find config file");
890
- });
891
- return stats.mtime.getTime().toString();
892
- }
893
- async function newConfig() {
894
- const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_load_from_file(), load_from_file_exports));
895
- await core2.init({
896
- config: loadConfig2(core2, buildConfig2)
897
- });
898
- return core2.getConfig();
899
- }
900
- return {
901
- core: core2,
902
- async getConfig() {
903
- const hash = await getConfigHash();
904
- if (loaded && loaded.hash === hash) return loaded.config;
905
- loaded = {
906
- hash,
907
- config: newConfig()
908
- };
909
- return loaded.config;
910
- }
911
- };
912
- }
913
-
914
- // src/core.ts
915
- var import_node_path4 = __toESM(require("path"), 1);
916
- var import_promises4 = __toESM(require("fs/promises"), 1);
917
-
918
- // src/utils/codegen.ts
919
- var import_node_path3 = __toESM(require("path"), 1);
920
- var import_tinyglobby = require("tinyglobby");
921
- function ident(code, tab = 1) {
922
- return code.split("\n").map((v) => " ".repeat(tab) + v).join("\n");
923
- }
924
-
925
- // src/core.ts
926
- async function getPlugins(pluginOptions) {
927
- const plugins = [];
928
- for await (const option of pluginOptions) {
929
- if (!option) continue;
930
- if (Array.isArray(option)) plugins.push(...await getPlugins(option));
931
- else plugins.push(option);
932
- }
933
- return plugins;
934
- }
935
- function createCore(options, defaultPlugins = []) {
936
- let config;
937
- let plugins;
938
- async function transformMetadata({
939
- collection,
940
- filePath,
941
- source
942
- }, data) {
943
- if (collection.schema) {
944
- data = await validate(
945
- collection.schema,
946
- data,
947
- { path: filePath, source },
948
- collection.type === "doc" ? `invalid frontmatter in ${filePath}` : `invalid data in ${filePath}`
949
- );
950
- }
951
- return data;
952
- }
953
- const core2 = {
954
- /**
955
- * Convenient cache store, reset when config changes
956
- */
957
- cache: /* @__PURE__ */ new Map(),
958
- async init({ config: newConfig }) {
959
- config = await newConfig;
960
- this.cache.clear();
961
- plugins = await getPlugins([
962
- postprocessPlugin(),
963
- ...defaultPlugins,
964
- ...config.global.plugins ?? []
965
- ]);
966
- for (const plugin of plugins) {
967
- const out = await plugin.config?.call(pluginContext, config);
968
- if (out) config = out;
969
- }
970
- },
971
- getOptions() {
972
- return options;
973
- },
974
- getConfig() {
975
- return config;
976
- },
977
- /**
978
- * The file path of compiled config file, the file may not exist (e.g. on Vite, or still compiling)
979
- */
980
- getCompiledConfigPath() {
981
- return import_node_path4.default.join(options.outDir, "source.config.mjs");
982
- },
983
- getPlugins() {
984
- return plugins;
985
- },
986
- getPluginContext() {
987
- return pluginContext;
988
- },
989
- async initServer(server) {
990
- for (const plugin of plugins) {
991
- await plugin.configureServer?.call(pluginContext, server);
992
- }
993
- },
994
- async emit({ filterPlugin = () => true } = {}) {
995
- return (await Promise.all(
996
- plugins.map((plugin) => {
997
- if (!filterPlugin(plugin) || !plugin.emit) return [];
998
- return plugin.emit.call(pluginContext);
999
- })
1000
- )).flat();
1001
- },
1002
- async emitAndWrite(emitOptions) {
1003
- const start = performance.now();
1004
- const out = await this.emit(emitOptions);
1005
- await Promise.all(
1006
- out.map(async (entry) => {
1007
- const file = import_node_path4.default.join(options.outDir, entry.path);
1008
- await import_promises4.default.mkdir(import_node_path4.default.dirname(file), { recursive: true });
1009
- await import_promises4.default.writeFile(file, entry.content);
1010
- })
1011
- );
1012
- console.log(`[MDX] generated files in ${performance.now() - start}ms`);
1013
- },
1014
- async transformMeta(options2, data) {
1015
- const ctx = {
1016
- ...pluginContext,
1017
- ...options2
1018
- };
1019
- data = await transformMetadata(options2, data);
1020
- for (const plugin of plugins) {
1021
- if (plugin.meta?.transform)
1022
- data = await plugin.meta.transform.call(ctx, data) ?? data;
1023
- }
1024
- return data;
1025
- },
1026
- async transformFrontmatter(options2, data) {
1027
- const ctx = {
1028
- ...pluginContext,
1029
- ...options2
1030
- };
1031
- data = await transformMetadata(options2, data);
1032
- for (const plugin of plugins) {
1033
- if (plugin.doc?.frontmatter)
1034
- data = await plugin.doc.frontmatter.call(ctx, data) ?? data;
1035
- }
1036
- return data;
1037
- },
1038
- async transformVFile(options2, file) {
1039
- const ctx = {
1040
- ...pluginContext,
1041
- ...options2
1042
- };
1043
- for (const plugin of plugins) {
1044
- if (plugin.doc?.vfile)
1045
- file = await plugin.doc.vfile.call(ctx, file) ?? file;
1046
- }
1047
- return file;
1048
- }
1049
- };
1050
- const pluginContext = {
1051
- core: core2,
1052
- ...options
1053
- };
1054
- return core2;
1055
- }
1056
- function postprocessPlugin() {
1057
- const LinkReferenceTypes = `{
1058
- /**
1059
- * extracted references (e.g. hrefs, paths), useful for analyzing relationships between pages.
1060
- */
1061
- extractedReferences?: import('fumadocs-mdx').ExtractedReference[];
1062
- }`;
1063
- return {
1064
- "index-file": {
1065
- generateTypeConfig() {
1066
- const lines = [];
1067
- lines.push("{");
1068
- lines.push(" DocData: {");
1069
- for (const collection of this.core.getConfig().collectionList) {
1070
- let postprocessOptions;
1071
- switch (collection.type) {
1072
- case "doc":
1073
- postprocessOptions = collection.postprocess;
1074
- break;
1075
- case "docs":
1076
- postprocessOptions = collection.docs.postprocess;
1077
- break;
1078
- }
1079
- if (postprocessOptions?.extractLinkReferences) {
1080
- lines.push(ident(`${collection.name}: ${LinkReferenceTypes},`, 2));
1081
- }
1082
- }
1083
- lines.push(" }");
1084
- lines.push("}");
1085
- return lines.join("\n");
1086
- },
1087
- serverOptions(options) {
1088
- options.doc ??= {};
1089
- options.doc.passthroughs ??= [];
1090
- options.doc.passthroughs.push("extractedReferences");
1091
- }
1092
- }
1093
- };
1094
- }
1095
-
1096
- // src/webpack/index.ts
1097
- var core;
1098
- function getCore(options) {
1099
- return core ??= createCore({
1100
- environment: "webpack",
1101
- outDir: options.outDir,
1102
- configPath: options.configPath
1103
- });
1104
- }
1105
-
1106
- // src/webpack/mdx.ts
1107
- var instance;
1108
- async function loader(source, callback) {
1109
- const options = this.getOptions();
1110
- this.cacheable(true);
1111
- this.addDependency(options.compiledConfigPath);
1112
- if (!instance) {
1113
- instance = toWebpack(
1114
- createMdxLoader(
1115
- createStandaloneConfigLoader({
1116
- core: getCore(options),
1117
- buildConfig: false,
1118
- mode: options.isDev ? "dev" : "production"
1119
- })
1120
- )
1121
- );
1122
- }
1123
- await instance.call(this, source, callback);
1124
- }