fumadocs-mdx 11.9.1 → 11.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/bin.cjs +1063 -0
  2. package/dist/bin.d.cts +1 -0
  3. package/dist/bin.d.ts +1 -0
  4. package/dist/bin.js +16 -0
  5. package/dist/{browser-CyU2Yl7A.d.cts → browser-B2G8uAF2.d.cts} +1 -1
  6. package/dist/{browser-DEsQvNRx.d.ts → browser-DrH7tKRi.d.ts} +1 -1
  7. package/dist/bun/index.cjs +669 -0
  8. package/dist/bun/index.d.cts +8 -0
  9. package/dist/bun/index.d.ts +8 -0
  10. package/dist/bun/index.js +53 -0
  11. package/dist/chunk-6Y5JDZHD.js +65 -0
  12. package/dist/chunk-CNKI574E.js +82 -0
  13. package/dist/{chunk-GX3THK2Q.js → chunk-IQAEAI4P.js} +25 -25
  14. package/dist/chunk-QJCCVMBJ.js +151 -0
  15. package/dist/{chunk-NUDEC6C5.js → chunk-UOOPSLFY.js} +1 -1
  16. package/dist/{chunk-COQ4VMK2.js → chunk-XXSKWWMB.js} +28 -61
  17. package/dist/config/index.d.cts +1 -1
  18. package/dist/config/index.d.ts +1 -1
  19. package/dist/config/zod-3.d.cts +1 -1
  20. package/dist/config/zod-3.d.ts +1 -1
  21. package/dist/{define-DnJzAZrj.d.cts → define-BH4bnHQl.d.cts} +6 -0
  22. package/dist/{define-DnJzAZrj.d.ts → define-BH4bnHQl.d.ts} +6 -0
  23. package/dist/loader-mdx.cjs +345 -265
  24. package/dist/loader-mdx.js +12 -80
  25. package/dist/next/index.cjs +15 -130
  26. package/dist/next/index.js +15 -33
  27. package/dist/node/loader.cjs +748 -0
  28. package/dist/node/loader.d.cts +5 -0
  29. package/dist/node/loader.d.ts +5 -0
  30. package/dist/node/loader.js +24 -0
  31. package/dist/postinstall-XV4WSHZP.js +9 -0
  32. package/dist/runtime/{async.cjs → next/async.cjs} +4 -4
  33. package/dist/runtime/{async.d.cts → next/async.d.cts} +3 -3
  34. package/dist/runtime/{async.d.ts → next/async.d.ts} +3 -3
  35. package/dist/runtime/{async.js → next/async.js} +6 -6
  36. package/dist/{index.cjs → runtime/next/index.cjs} +4 -6
  37. package/dist/{index.d.cts → runtime/next/index.d.cts} +3 -3
  38. package/dist/{index.d.ts → runtime/next/index.d.ts} +3 -3
  39. package/dist/{index.js → runtime/next/index.js} +1 -1
  40. package/dist/runtime/vite/browser.d.cts +2 -2
  41. package/dist/runtime/vite/browser.d.ts +2 -2
  42. package/dist/runtime/vite/server.d.cts +3 -3
  43. package/dist/runtime/vite/server.d.ts +3 -3
  44. package/dist/{types-WSHJKA8L.d.ts → types-DN9KrG7R.d.ts} +1 -1
  45. package/dist/{types-BmVgoqsr.d.cts → types-DT83Ijs6.d.cts} +1 -1
  46. package/dist/vite/index.cjs +440 -276
  47. package/dist/vite/index.d.cts +4 -1
  48. package/dist/vite/index.d.ts +4 -1
  49. package/dist/vite/index.js +19 -81
  50. package/package.json +24 -17
  51. package/bin.js +0 -5
  52. package/dist/chunk-UCY7OBZG.js +0 -12
@@ -0,0 +1,748 @@
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/mdx-plugins/remark-postprocess.ts
34
+ function remarkPostprocess({
35
+ injectExports
36
+ }) {
37
+ return (tree, file) => {
38
+ let title;
39
+ const urls = [];
40
+ (0, import_unist_util_visit.visit)(tree, ["heading", "link"], (node) => {
41
+ if (node.type === "heading" && node.depth === 1) {
42
+ title = flattenNode(node);
43
+ }
44
+ if (node.type !== "link") return;
45
+ urls.push({
46
+ href: node.url
47
+ });
48
+ return "skip";
49
+ });
50
+ if (title) {
51
+ file.data.frontmatter ??= {};
52
+ if (!file.data.frontmatter.title) file.data.frontmatter.title = title;
53
+ }
54
+ file.data.extractedReferences = urls;
55
+ for (const name of injectExports) {
56
+ if (!(name in file.data)) continue;
57
+ tree.children.unshift(getMdastExport(name, file.data[name]));
58
+ }
59
+ };
60
+ }
61
+ function flattenNode(node) {
62
+ if ("children" in node)
63
+ return node.children.map((child) => flattenNode(child)).join("");
64
+ if ("value" in node) return node.value;
65
+ return "";
66
+ }
67
+ function getMdastExport(name, value) {
68
+ return {
69
+ type: "mdxjsEsm",
70
+ value: "",
71
+ data: {
72
+ estree: {
73
+ type: "Program",
74
+ sourceType: "module",
75
+ body: [
76
+ {
77
+ type: "ExportNamedDeclaration",
78
+ attributes: [],
79
+ specifiers: [],
80
+ source: null,
81
+ declaration: {
82
+ type: "VariableDeclaration",
83
+ kind: "let",
84
+ declarations: [
85
+ {
86
+ type: "VariableDeclarator",
87
+ id: {
88
+ type: "Identifier",
89
+ name
90
+ },
91
+ init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
92
+ }
93
+ ]
94
+ }
95
+ }
96
+ ]
97
+ }
98
+ }
99
+ };
100
+ }
101
+ var import_unist_util_visit, import_estree_util_value_to_estree;
102
+ var init_remark_postprocess = __esm({
103
+ "src/mdx-plugins/remark-postprocess.ts"() {
104
+ "use strict";
105
+ import_unist_util_visit = require("unist-util-visit");
106
+ import_estree_util_value_to_estree = require("estree-util-value-to-estree");
107
+ }
108
+ });
109
+
110
+ // src/utils/mdx-options.ts
111
+ var mdx_options_exports = {};
112
+ __export(mdx_options_exports, {
113
+ getDefaultMDXOptions: () => getDefaultMDXOptions
114
+ });
115
+ function pluginOption(def, options = []) {
116
+ const list = def(Array.isArray(options) ? options : []).filter(
117
+ Boolean
118
+ );
119
+ if (typeof options === "function") {
120
+ return options(list);
121
+ }
122
+ return list;
123
+ }
124
+ function getDefaultMDXOptions({
125
+ valueToExport = [],
126
+ rehypeCodeOptions,
127
+ remarkImageOptions,
128
+ remarkHeadingOptions,
129
+ remarkStructureOptions,
130
+ remarkCodeTabOptions,
131
+ remarkNpmOptions,
132
+ _withoutBundler = false,
133
+ ...mdxOptions
134
+ }) {
135
+ const mdxExports = [
136
+ "structuredData",
137
+ "extractedReferences",
138
+ "frontmatter",
139
+ "lastModified",
140
+ ...valueToExport
141
+ ];
142
+ const remarkPlugins = pluginOption(
143
+ (v) => [
144
+ plugins.remarkGfm,
145
+ [
146
+ plugins.remarkHeading,
147
+ {
148
+ generateToc: false,
149
+ ...remarkHeadingOptions
150
+ }
151
+ ],
152
+ remarkImageOptions !== false && [
153
+ plugins.remarkImage,
154
+ {
155
+ ...remarkImageOptions,
156
+ useImport: _withoutBundler ? false : remarkImageOptions?.useImport
157
+ }
158
+ ],
159
+ "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
160
+ plugins.remarkCodeTab,
161
+ remarkCodeTabOptions
162
+ ],
163
+ "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
164
+ ...v,
165
+ remarkStructureOptions !== false && [
166
+ plugins.remarkStructure,
167
+ remarkStructureOptions
168
+ ],
169
+ [
170
+ remarkPostprocess,
171
+ { injectExports: mdxExports }
172
+ ]
173
+ ],
174
+ mdxOptions.remarkPlugins
175
+ );
176
+ const rehypePlugins = pluginOption(
177
+ (v) => [
178
+ rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
179
+ ...v,
180
+ plugins.rehypeToc
181
+ ],
182
+ mdxOptions.rehypePlugins
183
+ );
184
+ return {
185
+ ...mdxOptions,
186
+ outputFormat: _withoutBundler ? "function-body" : mdxOptions.outputFormat,
187
+ remarkPlugins,
188
+ rehypePlugins
189
+ };
190
+ }
191
+ var plugins;
192
+ var init_mdx_options = __esm({
193
+ "src/utils/mdx-options.ts"() {
194
+ "use strict";
195
+ plugins = __toESM(require("fumadocs-core/mdx-plugins"), 1);
196
+ init_remark_postprocess();
197
+ }
198
+ });
199
+
200
+ // src/node/loader.ts
201
+ var loader_exports = {};
202
+ __export(loader_exports, {
203
+ load: () => load2
204
+ });
205
+ module.exports = __toCommonJS(loader_exports);
206
+
207
+ // src/utils/config.ts
208
+ var fs = __toESM(require("fs/promises"), 1);
209
+ var path = __toESM(require("path"), 1);
210
+ var import_node_url = require("url");
211
+
212
+ // src/config/build.ts
213
+ function buildConfig(config) {
214
+ const collections = /* @__PURE__ */ new Map();
215
+ let globalConfig = {};
216
+ for (const [k, v] of Object.entries(config)) {
217
+ if (!v) {
218
+ continue;
219
+ }
220
+ if (typeof v === "object" && "type" in v) {
221
+ if (v.type === "docs") {
222
+ collections.set(k, v);
223
+ continue;
224
+ }
225
+ if (v.type === "doc" || v.type === "meta") {
226
+ collections.set(k, v);
227
+ continue;
228
+ }
229
+ }
230
+ if (k === "default" && v) {
231
+ globalConfig = v;
232
+ continue;
233
+ }
234
+ throw new Error(
235
+ `Unknown export "${k}", you can only export collections from source configuration file.`
236
+ );
237
+ }
238
+ const mdxOptionsCache = /* @__PURE__ */ new Map();
239
+ return {
240
+ global: globalConfig,
241
+ collections,
242
+ async getDefaultMDXOptions(mode = "default") {
243
+ const cached = mdxOptionsCache.get(mode);
244
+ if (cached) return cached;
245
+ const input = this.global.mdxOptions;
246
+ async function uncached() {
247
+ const options = typeof input === "function" ? await input() : input;
248
+ const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_mdx_options(), mdx_options_exports));
249
+ if (options?.preset === "minimal") return options;
250
+ return getDefaultMDXOptions2({
251
+ ...options,
252
+ _withoutBundler: mode === "remote"
253
+ });
254
+ }
255
+ const result = uncached();
256
+ mdxOptionsCache.set(mode, result);
257
+ return result;
258
+ }
259
+ };
260
+ }
261
+
262
+ // src/utils/config.ts
263
+ function findConfigFile() {
264
+ return path.resolve("source.config.ts");
265
+ }
266
+ var cache = null;
267
+ async function isZod3() {
268
+ try {
269
+ const content = JSON.parse(
270
+ (await fs.readFile("node_modules/zod/package.json")).toString()
271
+ );
272
+ const version = content.version;
273
+ return typeof version === "string" && version.startsWith("3.");
274
+ } catch {
275
+ return false;
276
+ }
277
+ }
278
+ function createCompatZodPlugin() {
279
+ return {
280
+ name: "replace-zod-import",
281
+ async setup(build) {
282
+ const usingZod3 = await isZod3();
283
+ if (!usingZod3) return;
284
+ console.warn(
285
+ "[Fumadocs MDX] Noticed Zod v3 in your node_modules, we recommend upgrading to Zod v4 for better compatibility."
286
+ );
287
+ build.onResolve({ filter: /^fumadocs-mdx\/config$/ }, () => {
288
+ return {
289
+ path: "fumadocs-mdx/config/zod-3",
290
+ external: true
291
+ };
292
+ });
293
+ }
294
+ };
295
+ }
296
+ async function compileConfig(configPath, outDir) {
297
+ const { build } = await import("esbuild");
298
+ const transformed = await build({
299
+ entryPoints: [{ in: configPath, out: "source.config" }],
300
+ bundle: true,
301
+ outdir: outDir,
302
+ target: "node20",
303
+ write: true,
304
+ platform: "node",
305
+ format: "esm",
306
+ packages: "external",
307
+ plugins: [createCompatZodPlugin()],
308
+ outExtension: {
309
+ ".js": ".mjs"
310
+ },
311
+ allowOverwrite: true
312
+ });
313
+ if (transformed.errors.length > 0) {
314
+ throw new Error("failed to compile configuration file");
315
+ }
316
+ }
317
+ async function loadConfig(configPath, outDir, hash, build = false) {
318
+ if (cache && cache.hash === hash) {
319
+ return await cache.config;
320
+ }
321
+ if (build) await compileConfig(configPath, outDir);
322
+ const url = (0, import_node_url.pathToFileURL)(path.resolve(outDir, "source.config.mjs"));
323
+ const config = import(`${url.href}?hash=${hash}`).then((loaded) => {
324
+ return buildConfig(
325
+ // every call to `loadConfig` will cause the previous cache to be ignored
326
+ loaded
327
+ );
328
+ });
329
+ if (hash) cache = { config, hash };
330
+ return await config;
331
+ }
332
+ async function getConfigHash(configPath) {
333
+ const stats = await fs.stat(configPath).catch(() => void 0);
334
+ if (stats) {
335
+ return stats.mtime.getTime().toString();
336
+ }
337
+ throw new Error("Cannot find config file");
338
+ }
339
+
340
+ // src/utils/fuma-matter.ts
341
+ var import_js_yaml = require("js-yaml");
342
+ var regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
343
+ function fumaMatter(input) {
344
+ const output = { matter: "", data: {}, content: input };
345
+ const match = regex.exec(input);
346
+ if (!match) {
347
+ return output;
348
+ }
349
+ output.matter = match[0];
350
+ output.content = input.slice(match[0].length);
351
+ const loaded = (0, import_js_yaml.load)(match[1]);
352
+ output.data = loaded ?? {};
353
+ return output;
354
+ }
355
+
356
+ // src/utils/validation.ts
357
+ var import_picocolors = __toESM(require("picocolors"), 1);
358
+ var ValidationError = class extends Error {
359
+ constructor(message, issues) {
360
+ super(
361
+ `${message}:
362
+ ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
363
+ );
364
+ this.title = message;
365
+ this.issues = issues;
366
+ }
367
+ toStringFormatted() {
368
+ return [
369
+ import_picocolors.default.bold(`[MDX] ${this.title}:`),
370
+ ...this.issues.map(
371
+ (issue) => import_picocolors.default.redBright(
372
+ `- ${import_picocolors.default.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
373
+ )
374
+ )
375
+ ].join("\n");
376
+ }
377
+ };
378
+ async function validate(schema, data, context, errorMessage) {
379
+ if (typeof schema === "function" && !("~standard" in schema)) {
380
+ schema = schema(context);
381
+ }
382
+ if ("~standard" in schema) {
383
+ const result = await schema["~standard"].validate(
384
+ data
385
+ );
386
+ if (result.issues) {
387
+ throw new ValidationError(errorMessage, result.issues);
388
+ }
389
+ return result.value;
390
+ }
391
+ return data;
392
+ }
393
+
394
+ // src/utils/git-timestamp.ts
395
+ var import_node_path = __toESM(require("path"), 1);
396
+ var import_tinyexec = require("tinyexec");
397
+ var cache2 = /* @__PURE__ */ new Map();
398
+ async function getGitTimestamp(file) {
399
+ const cached = cache2.get(file);
400
+ if (cached) return cached;
401
+ try {
402
+ const out = await (0, import_tinyexec.x)(
403
+ "git",
404
+ ["log", "-1", '--pretty="%ai"', import_node_path.default.relative(process.cwd(), file)],
405
+ {
406
+ throwOnError: true
407
+ }
408
+ );
409
+ const time = new Date(out.stdout);
410
+ cache2.set(file, time);
411
+ return time;
412
+ } catch {
413
+ return;
414
+ }
415
+ }
416
+
417
+ // src/utils/count-lines.ts
418
+ function countLines(s) {
419
+ let num = 0;
420
+ for (const c of s) {
421
+ if (c === "\n") num++;
422
+ }
423
+ return num;
424
+ }
425
+
426
+ // src/utils/build-mdx.ts
427
+ var import_mdx = require("@mdx-js/mdx");
428
+
429
+ // src/mdx-plugins/remark-include.ts
430
+ var import_unified = require("unified");
431
+ var import_unist_util_visit2 = require("unist-util-visit");
432
+ var path3 = __toESM(require("path"), 1);
433
+ var fs2 = __toESM(require("fs/promises"), 1);
434
+ var import_remark_parse = __toESM(require("remark-parse"), 1);
435
+ var import_remark_mdx = __toESM(require("remark-mdx"), 1);
436
+ var import_mdx_plugins = require("fumadocs-core/mdx-plugins");
437
+ var baseProcessor = (0, import_unified.unified)().use(import_mdx_plugins.remarkHeading);
438
+ function flattenNode2(node) {
439
+ if ("children" in node)
440
+ return node.children.map((child) => flattenNode2(child)).join("");
441
+ if ("value" in node) return node.value;
442
+ return "";
443
+ }
444
+ function parseSpecifier(specifier) {
445
+ const idx = specifier.lastIndexOf("#");
446
+ if (idx === -1) return { file: specifier };
447
+ return {
448
+ file: specifier.slice(0, idx),
449
+ section: specifier.slice(idx + 1)
450
+ };
451
+ }
452
+ function extractSection(root, section) {
453
+ let nodes;
454
+ for (const node of root.children) {
455
+ if (node.type === "mdxJsxFlowElement" && node.name === "section" && node.attributes.some(
456
+ (attr) => attr.type === "mdxJsxAttribute" && attr.name === "id" && attr.value === section
457
+ )) {
458
+ nodes = node.children;
459
+ break;
460
+ }
461
+ if (node.type === "heading" && node.data?.hProperties?.id === section) {
462
+ nodes = [node];
463
+ continue;
464
+ }
465
+ if (!nodes) continue;
466
+ if (node.type === "heading") break;
467
+ nodes.push(node);
468
+ }
469
+ if (nodes)
470
+ return {
471
+ type: "root",
472
+ children: nodes
473
+ };
474
+ }
475
+ function remarkInclude() {
476
+ const TagName = "include";
477
+ async function embedContent(file, heading, params, data) {
478
+ let content;
479
+ try {
480
+ content = (await fs2.readFile(file)).toString();
481
+ } catch (e) {
482
+ throw new Error(
483
+ `failed to read file ${file}
484
+ ${e instanceof Error ? e.message : String(e)}`,
485
+ { cause: e }
486
+ );
487
+ }
488
+ const ext = path3.extname(file);
489
+ data._compiler?.addDependency(file);
490
+ if (params.lang || ext !== ".md" && ext !== ".mdx") {
491
+ const lang = params.lang ?? ext.slice(1);
492
+ return {
493
+ type: "code",
494
+ lang,
495
+ meta: params.meta,
496
+ value: content,
497
+ data: {}
498
+ };
499
+ }
500
+ const processor = (data._getProcessor ?? getDefaultProcessor)(
501
+ ext === ".mdx" ? "mdx" : "md"
502
+ );
503
+ let parsed = await baseProcessor.run(
504
+ processor.parse(fumaMatter(content).content)
505
+ );
506
+ if (heading) {
507
+ const extracted = extractSection(parsed, heading);
508
+ if (!extracted)
509
+ throw new Error(
510
+ `Cannot find section ${heading} in ${file}, make sure you have encapsulated the section in a <section id="${heading}"> tag.`
511
+ );
512
+ parsed = extracted;
513
+ }
514
+ await update(parsed, path3.dirname(file), data);
515
+ return parsed;
516
+ }
517
+ async function update(tree, directory, data) {
518
+ const queue = [];
519
+ (0, import_unist_util_visit2.visit)(
520
+ tree,
521
+ ["mdxJsxFlowElement", "mdxJsxTextElement"],
522
+ (_node, _, parent) => {
523
+ const node = _node;
524
+ if (node.name !== TagName) return;
525
+ const params = {};
526
+ const specifier = flattenNode2(node);
527
+ if (specifier.length === 0) return "skip";
528
+ for (const attr of node.attributes) {
529
+ if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
530
+ params[attr.name] = attr.value;
531
+ }
532
+ }
533
+ const { file: relativePath, section } = parseSpecifier(specifier);
534
+ const file = path3.resolve(
535
+ "cwd" in params ? process.cwd() : directory,
536
+ relativePath
537
+ );
538
+ queue.push(
539
+ embedContent(file, section, params, data).then((replace) => {
540
+ Object.assign(
541
+ parent && parent.type === "paragraph" ? parent : node,
542
+ replace
543
+ );
544
+ })
545
+ );
546
+ return "skip";
547
+ }
548
+ );
549
+ await Promise.all(queue);
550
+ }
551
+ return async (tree, file) => {
552
+ await update(tree, path3.dirname(file.path), file.data);
553
+ };
554
+ }
555
+ function getDefaultProcessor(format) {
556
+ const mdProcessor = (0, import_unified.unified)().use(import_remark_parse.default);
557
+ if (format === "md") return mdProcessor;
558
+ return mdProcessor.use(import_remark_mdx.default);
559
+ }
560
+
561
+ // src/utils/build-mdx.ts
562
+ var cache3 = /* @__PURE__ */ new Map();
563
+ async function buildMDX(cacheKey, source, options) {
564
+ const { filePath, frontmatter, data, _compiler, ...rest } = options;
565
+ function getProcessor(format) {
566
+ const key = `${cacheKey}:${format}`;
567
+ let processor = cache3.get(key);
568
+ if (!processor) {
569
+ processor = (0, import_mdx.createProcessor)({
570
+ outputFormat: "program",
571
+ ...rest,
572
+ remarkPlugins: [remarkInclude, ...rest.remarkPlugins ?? []],
573
+ format
574
+ });
575
+ cache3.set(key, processor);
576
+ }
577
+ return processor;
578
+ }
579
+ return getProcessor(
580
+ options.format ?? filePath.endsWith(".mdx") ? "mdx" : "md"
581
+ ).process({
582
+ value: source,
583
+ path: filePath,
584
+ data: {
585
+ ...data,
586
+ frontmatter,
587
+ _compiler,
588
+ _getProcessor: getProcessor
589
+ }
590
+ });
591
+ }
592
+
593
+ // src/loaders/mdx.ts
594
+ var import_zod = require("zod");
595
+ var import_promises = __toESM(require("fs/promises"), 1);
596
+ var import_node_path2 = __toESM(require("path"), 1);
597
+ var import_node_crypto = require("crypto");
598
+ var querySchema = import_zod.z.object({
599
+ only: import_zod.z.literal(["frontmatter", "all"]).default("all"),
600
+ collection: import_zod.z.string().optional(),
601
+ hash: import_zod.z.string().describe(
602
+ "the hash of config, used for revalidation on Turbopack/Webpack."
603
+ ).optional()
604
+ }).loose();
605
+ var cacheEntry = import_zod.z.object({
606
+ code: import_zod.z.string(),
607
+ map: import_zod.z.any().optional(),
608
+ hash: import_zod.z.string().optional()
609
+ });
610
+ function createMdxLoader(configLoader) {
611
+ return async ({
612
+ source: value,
613
+ development: isDevelopment,
614
+ query,
615
+ compiler,
616
+ filePath
617
+ }) => {
618
+ const matter = fumaMatter(value);
619
+ const parsed = querySchema.parse(query);
620
+ const loaded = await configLoader.getConfig(parsed.hash);
621
+ const cacheDir = isDevelopment ? void 0 : loaded.global.experimentalBuildCache;
622
+ const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
623
+ if (cacheDir) {
624
+ const cached = await import_promises.default.readFile(import_node_path2.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
625
+ if (cached && cached.hash === generateCacheHash(value)) return cached;
626
+ }
627
+ const collection = parsed.collection ? loaded.collections.get(parsed.collection) : void 0;
628
+ let schema;
629
+ let mdxOptions;
630
+ switch (collection?.type) {
631
+ case "doc":
632
+ mdxOptions = collection.mdxOptions;
633
+ schema = collection.schema;
634
+ break;
635
+ case "docs":
636
+ mdxOptions = collection.docs.mdxOptions;
637
+ schema = collection.docs.schema;
638
+ break;
639
+ }
640
+ if (schema) {
641
+ matter.data = await validate(
642
+ schema,
643
+ matter.data,
644
+ {
645
+ source: value,
646
+ path: filePath
647
+ },
648
+ `invalid frontmatter in ${filePath}`
649
+ );
650
+ }
651
+ if (parsed.only === "frontmatter") {
652
+ return {
653
+ code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
654
+ map: null
655
+ };
656
+ }
657
+ const data = {};
658
+ if (loaded.global.lastModifiedTime === "git") {
659
+ data.lastModified = (await getGitTimestamp(filePath))?.getTime();
660
+ }
661
+ const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
662
+ const compiled = await buildMDX(
663
+ `${parsed.hash ?? ""}:${parsed.collection ?? "global"}`,
664
+ "\n".repeat(lineOffset) + matter.content,
665
+ {
666
+ development: isDevelopment,
667
+ ...mdxOptions ?? await loaded.getDefaultMDXOptions(),
668
+ data,
669
+ filePath,
670
+ frontmatter: matter.data,
671
+ _compiler: compiler
672
+ }
673
+ );
674
+ const out = {
675
+ code: String(compiled.value),
676
+ map: compiled.map
677
+ };
678
+ if (cacheDir) {
679
+ await import_promises.default.mkdir(cacheDir, { recursive: true });
680
+ await import_promises.default.writeFile(
681
+ import_node_path2.default.join(cacheDir, cacheKey),
682
+ JSON.stringify({
683
+ ...out,
684
+ hash: generateCacheHash(value)
685
+ })
686
+ );
687
+ }
688
+ return out;
689
+ };
690
+ }
691
+ function generateCacheHash(input) {
692
+ return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
693
+ }
694
+
695
+ // src/loaders/config-loader.ts
696
+ function dynamicConfig(configPath, outDir) {
697
+ return {
698
+ async getConfig(hash) {
699
+ return loadConfig(
700
+ configPath,
701
+ outDir,
702
+ hash ?? await getConfigHash(configPath)
703
+ );
704
+ }
705
+ };
706
+ }
707
+
708
+ // src/loaders/adapter.ts
709
+ var import_node_url2 = require("url");
710
+ var import_promises2 = __toESM(require("fs/promises"), 1);
711
+ var import_node_querystring = require("querystring");
712
+ var import_node_path3 = __toESM(require("path"), 1);
713
+ function toNode(loader, filterByPath) {
714
+ return async (url, _context, nextLoad) => {
715
+ if (!url.startsWith("file:///")) return nextLoad(url);
716
+ const parsedUrl = new URL(url);
717
+ const filePath = (0, import_node_url2.fileURLToPath)(parsedUrl);
718
+ if (filterByPath(filePath)) {
719
+ const source = (await import_promises2.default.readFile(filePath)).toString();
720
+ const result = await loader({
721
+ filePath,
722
+ query: Object.fromEntries(parsedUrl.searchParams.entries()),
723
+ source,
724
+ development: false,
725
+ compiler: {
726
+ addDependency() {
727
+ }
728
+ }
729
+ });
730
+ return {
731
+ source: result.code,
732
+ format: "module",
733
+ shortCircuit: true
734
+ };
735
+ }
736
+ return nextLoad(url);
737
+ };
738
+ }
739
+
740
+ // src/node/loader.ts
741
+ var load2 = toNode(
742
+ createMdxLoader(dynamicConfig(findConfigFile(), ".source")),
743
+ (filePath) => filePath.endsWith(".md") || filePath.endsWith(".mdx")
744
+ );
745
+ // Annotate the CommonJS export names for ESM import in node:
746
+ 0 && (module.exports = {
747
+ load
748
+ });