fumadocs-mdx 11.6.0 → 13.0.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 (93) hide show
  1. package/dist/bin.cjs +1728 -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/build-mdx-CCNr86q6.d.ts +53 -0
  6. package/dist/build-mdx-D-r3_eQL.d.cts +53 -0
  7. package/dist/bun/index.cjs +857 -0
  8. package/dist/bun/index.d.cts +13 -0
  9. package/dist/bun/index.d.ts +13 -0
  10. package/dist/bun/index.js +62 -0
  11. package/dist/chunk-3J3WL7WN.js +160 -0
  12. package/dist/chunk-CXA4JO4Z.js +45 -0
  13. package/dist/chunk-EELYB2XC.js +207 -0
  14. package/dist/chunk-FSZMKRVH.js +80 -0
  15. package/dist/chunk-II3H5ZVZ.js +77 -0
  16. package/dist/chunk-JVZFH6ND.js +40 -0
  17. package/dist/chunk-K5ZLPEIQ.js +207 -0
  18. package/dist/{chunk-VFALQK6O.js → chunk-KILFIBVW.js} +21 -12
  19. package/dist/chunk-NVRDCY6Z.js +30 -0
  20. package/dist/chunk-U4MQ44TS.js +53 -0
  21. package/dist/chunk-VWJKRQZR.js +19 -0
  22. package/dist/chunk-XQ5O7IPO.js +128 -0
  23. package/dist/chunk-XZY2AWJI.js +81 -0
  24. package/dist/chunk-YVCR6FUH.js +82 -0
  25. package/dist/config/index.cjs +232 -128
  26. package/dist/config/index.d.cts +4 -6
  27. package/dist/config/index.d.ts +4 -6
  28. package/dist/config/index.js +26 -19
  29. package/dist/core-B6j6Fxse.d.cts +218 -0
  30. package/dist/core-B6j6Fxse.d.ts +218 -0
  31. package/dist/index.cjs +0 -76
  32. package/dist/index.d.cts +73 -20
  33. package/dist/index.d.ts +73 -20
  34. package/dist/index.js +0 -10
  35. package/dist/load-MNG3CLET.js +7 -0
  36. package/dist/next/index.cjs +567 -314
  37. package/dist/next/index.d.cts +9 -12
  38. package/dist/next/index.d.ts +9 -12
  39. package/dist/next/index.js +238 -211
  40. package/dist/node/loader.cjs +922 -0
  41. package/dist/node/loader.d.cts +5 -0
  42. package/dist/node/loader.d.ts +5 -0
  43. package/dist/node/loader.js +33 -0
  44. package/dist/plugins/json-schema.cjs +162 -0
  45. package/dist/plugins/json-schema.d.cts +24 -0
  46. package/dist/plugins/json-schema.d.ts +24 -0
  47. package/dist/plugins/json-schema.js +78 -0
  48. package/dist/{mdx-options-CAU273O3.js → preset-ZMP6U62C.js} +1 -1
  49. package/dist/runtime/next/async.cjs +715 -0
  50. package/dist/runtime/next/async.d.cts +21 -0
  51. package/dist/runtime/next/async.d.ts +21 -0
  52. package/dist/runtime/next/async.js +89 -0
  53. package/dist/runtime/next/index.cjs +136 -0
  54. package/dist/runtime/next/index.d.cts +33 -0
  55. package/dist/runtime/next/index.d.ts +33 -0
  56. package/dist/runtime/next/index.js +11 -0
  57. package/dist/runtime/vite/browser.cjs +107 -0
  58. package/dist/runtime/vite/browser.d.cts +59 -0
  59. package/dist/runtime/vite/browser.d.ts +59 -0
  60. package/dist/runtime/vite/browser.js +11 -0
  61. package/dist/runtime/vite/server.cjs +243 -0
  62. package/dist/runtime/vite/server.d.cts +30 -0
  63. package/dist/runtime/vite/server.d.ts +30 -0
  64. package/dist/runtime/vite/server.js +111 -0
  65. package/dist/types-AGzTfBmf.d.ts +45 -0
  66. package/dist/types-DKGMoay5.d.cts +45 -0
  67. package/dist/vite/index.cjs +1185 -0
  68. package/dist/vite/index.d.cts +45 -0
  69. package/dist/vite/index.d.ts +45 -0
  70. package/dist/vite/index.js +297 -0
  71. package/dist/webpack/index.cjs +957 -0
  72. package/dist/{loader-mdx.d.cts → webpack/index.d.cts} +3 -6
  73. package/dist/{loader-mdx.d.ts → webpack/index.d.ts} +3 -6
  74. package/dist/webpack/index.js +44 -0
  75. package/loader-mdx.cjs +1 -1
  76. package/package.json +86 -29
  77. package/bin.js +0 -5
  78. package/dist/chunk-2ZOW45YZ.js +0 -63
  79. package/dist/chunk-DRVUBK5B.js +0 -39
  80. package/dist/chunk-HFLDWPJA.js +0 -62
  81. package/dist/chunk-IOENRFUX.js +0 -112
  82. package/dist/chunk-MK7EXW7O.js +0 -75
  83. package/dist/define-BaW0PQDJ.d.cts +0 -201
  84. package/dist/define-BaW0PQDJ.d.ts +0 -201
  85. package/dist/loader-mdx.cjs +0 -527
  86. package/dist/loader-mdx.js +0 -162
  87. package/dist/runtime/async.cjs +0 -269
  88. package/dist/runtime/async.d.cts +0 -18
  89. package/dist/runtime/async.d.ts +0 -18
  90. package/dist/runtime/async.js +0 -73
  91. package/dist/types-BNrQHCj5.d.cts +0 -100
  92. package/dist/types-DEduCvIT.d.ts +0 -100
  93. package/dist/watcher-IAZDSTU7.js +0 -24
@@ -0,0 +1,922 @@
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/loaders/mdx/preset.ts
34
+ var preset_exports = {};
35
+ __export(preset_exports, {
36
+ getDefaultMDXOptions: () => getDefaultMDXOptions
37
+ });
38
+ function pluginOption(def, options = []) {
39
+ const list = def(Array.isArray(options) ? options : []).filter(
40
+ Boolean
41
+ );
42
+ if (typeof options === "function") {
43
+ return options(list);
44
+ }
45
+ return list;
46
+ }
47
+ function getDefaultMDXOptions({
48
+ valueToExport = [],
49
+ rehypeCodeOptions,
50
+ remarkImageOptions,
51
+ remarkHeadingOptions,
52
+ remarkStructureOptions,
53
+ remarkCodeTabOptions,
54
+ remarkNpmOptions,
55
+ _withoutBundler = false,
56
+ ...mdxOptions
57
+ }) {
58
+ const remarkPlugins = pluginOption(
59
+ (v) => [
60
+ plugins.remarkGfm,
61
+ [
62
+ plugins.remarkHeading,
63
+ {
64
+ generateToc: false,
65
+ ...remarkHeadingOptions
66
+ }
67
+ ],
68
+ remarkImageOptions !== false && [
69
+ plugins.remarkImage,
70
+ {
71
+ ...remarkImageOptions,
72
+ useImport: _withoutBundler ? false : remarkImageOptions?.useImport
73
+ }
74
+ ],
75
+ "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && [
76
+ plugins.remarkCodeTab,
77
+ remarkCodeTabOptions
78
+ ],
79
+ "remarkNpm" in plugins && remarkNpmOptions !== false && [plugins.remarkNpm, remarkNpmOptions],
80
+ ...v,
81
+ remarkStructureOptions !== false && [
82
+ plugins.remarkStructure,
83
+ remarkStructureOptions
84
+ ],
85
+ () => {
86
+ return (_, file) => {
87
+ file.data["mdx-export"] ??= [];
88
+ for (const name of valueToExport) {
89
+ if (name in file.data)
90
+ file.data["mdx-export"].push({ name, value: file.data[name] });
91
+ }
92
+ };
93
+ }
94
+ ],
95
+ mdxOptions.remarkPlugins
96
+ );
97
+ const rehypePlugins = pluginOption(
98
+ (v) => [
99
+ rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
100
+ ...v,
101
+ plugins.rehypeToc
102
+ ],
103
+ mdxOptions.rehypePlugins
104
+ );
105
+ return {
106
+ ...mdxOptions,
107
+ outputFormat: _withoutBundler ? "function-body" : mdxOptions.outputFormat,
108
+ remarkPlugins,
109
+ rehypePlugins
110
+ };
111
+ }
112
+ var plugins;
113
+ var init_preset = __esm({
114
+ "src/loaders/mdx/preset.ts"() {
115
+ "use strict";
116
+ plugins = __toESM(require("fumadocs-core/mdx-plugins"), 1);
117
+ }
118
+ });
119
+
120
+ // src/config/build.ts
121
+ function buildConfig(config) {
122
+ const collections = /* @__PURE__ */ new Map();
123
+ let globalConfig = {};
124
+ for (const [k, v] of Object.entries(config)) {
125
+ if (!v) {
126
+ continue;
127
+ }
128
+ if (typeof v === "object" && "type" in v) {
129
+ if (v.type === "docs") {
130
+ collections.set(k, v);
131
+ continue;
132
+ }
133
+ if (v.type === "doc" || v.type === "meta") {
134
+ collections.set(k, v);
135
+ continue;
136
+ }
137
+ }
138
+ if (k === "default" && v) {
139
+ globalConfig = v;
140
+ continue;
141
+ }
142
+ throw new Error(
143
+ `Unknown export "${k}", you can only export collections from source configuration file.`
144
+ );
145
+ }
146
+ const mdxOptionsCache = /* @__PURE__ */ new Map();
147
+ return {
148
+ global: globalConfig,
149
+ collections,
150
+ async getDefaultMDXOptions(mode = "default") {
151
+ const cached = mdxOptionsCache.get(mode);
152
+ if (cached) return cached;
153
+ const input = this.global.mdxOptions;
154
+ async function uncached() {
155
+ const options = typeof input === "function" ? await input() : input;
156
+ const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_preset(), preset_exports));
157
+ if (options?.preset === "minimal") return options;
158
+ return getDefaultMDXOptions2({
159
+ ...options,
160
+ _withoutBundler: mode === "remote"
161
+ });
162
+ }
163
+ const result = uncached();
164
+ mdxOptionsCache.set(mode, result);
165
+ return result;
166
+ }
167
+ };
168
+ }
169
+ var init_build = __esm({
170
+ "src/config/build.ts"() {
171
+ "use strict";
172
+ }
173
+ });
174
+
175
+ // src/loaders/config/load.ts
176
+ var load_exports = {};
177
+ __export(load_exports, {
178
+ loadConfig: () => loadConfig
179
+ });
180
+ async function compileConfig(configPath, outDir) {
181
+ const { build } = await import("esbuild");
182
+ const transformed = await build({
183
+ entryPoints: [{ in: configPath, out: "source.config" }],
184
+ bundle: true,
185
+ outdir: outDir,
186
+ target: "node20",
187
+ write: true,
188
+ platform: "node",
189
+ format: "esm",
190
+ packages: "external",
191
+ outExtension: {
192
+ ".js": ".mjs"
193
+ },
194
+ allowOverwrite: true
195
+ });
196
+ if (transformed.errors.length > 0) {
197
+ throw new Error("failed to compile configuration file");
198
+ }
199
+ }
200
+ async function loadConfig(configPath, outDir, build = false) {
201
+ if (build) await compileConfig(configPath, outDir);
202
+ const url = (0, import_node_url.pathToFileURL)(path.resolve(outDir, "source.config.mjs"));
203
+ url.searchParams.set("hash", Date.now().toString());
204
+ const config = import(url.href).then(
205
+ (loaded) => buildConfig(loaded)
206
+ );
207
+ return await config;
208
+ }
209
+ var path, import_node_url;
210
+ var init_load = __esm({
211
+ "src/loaders/config/load.ts"() {
212
+ "use strict";
213
+ path = __toESM(require("path"), 1);
214
+ import_node_url = require("url");
215
+ init_build();
216
+ }
217
+ });
218
+
219
+ // src/node/loader.ts
220
+ var loader_exports = {};
221
+ __export(loader_exports, {
222
+ load: () => load2
223
+ });
224
+ module.exports = __toCommonJS(loader_exports);
225
+
226
+ // src/loaders/config/index.ts
227
+ var import_node_path = __toESM(require("path"), 1);
228
+ var import_promises = __toESM(require("fs/promises"), 1);
229
+ function findConfigFile() {
230
+ return import_node_path.default.resolve("source.config.ts");
231
+ }
232
+ function staticConfig({
233
+ core: core2,
234
+ buildConfig: buildConfig2
235
+ }) {
236
+ let cached;
237
+ async function newConfig() {
238
+ const { loadConfig: loadConfig2 } = await Promise.resolve().then(() => (init_load(), load_exports));
239
+ await core2.init({
240
+ config: loadConfig2(
241
+ core2._options.configPath,
242
+ core2._options.outDir,
243
+ buildConfig2
244
+ )
245
+ });
246
+ return core2.getConfig();
247
+ }
248
+ return {
249
+ async getConfig() {
250
+ return cached ??= newConfig();
251
+ }
252
+ };
253
+ }
254
+
255
+ // src/utils/fuma-matter.ts
256
+ var import_js_yaml = require("js-yaml");
257
+ var regex = /^---\r?\n(.+?)\r?\n---\r?\n/s;
258
+ function fumaMatter(input) {
259
+ const output = { matter: "", data: {}, content: input };
260
+ const match = regex.exec(input);
261
+ if (!match) {
262
+ return output;
263
+ }
264
+ output.matter = match[0];
265
+ output.content = input.slice(match[0].length);
266
+ const loaded = (0, import_js_yaml.load)(match[1]);
267
+ output.data = loaded ?? {};
268
+ return output;
269
+ }
270
+
271
+ // src/utils/validation.ts
272
+ var import_picocolors = __toESM(require("picocolors"), 1);
273
+ var ValidationError = class extends Error {
274
+ constructor(message, issues) {
275
+ super(
276
+ `${message}:
277
+ ${issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`
278
+ );
279
+ this.title = message;
280
+ this.issues = issues;
281
+ }
282
+ toStringFormatted() {
283
+ return [
284
+ import_picocolors.default.bold(`[MDX] ${this.title}:`),
285
+ ...this.issues.map(
286
+ (issue) => import_picocolors.default.redBright(
287
+ `- ${import_picocolors.default.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
288
+ )
289
+ )
290
+ ].join("\n");
291
+ }
292
+ };
293
+ async function validate(schema, data, context, errorMessage) {
294
+ if (typeof schema === "function" && !("~standard" in schema)) {
295
+ schema = schema(context);
296
+ }
297
+ if ("~standard" in schema) {
298
+ const result = await schema["~standard"].validate(
299
+ data
300
+ );
301
+ if (result.issues) {
302
+ throw new ValidationError(errorMessage, result.issues);
303
+ }
304
+ return result.value;
305
+ }
306
+ return data;
307
+ }
308
+
309
+ // src/utils/git-timestamp.ts
310
+ var import_node_path2 = __toESM(require("path"), 1);
311
+ var import_tinyexec = require("tinyexec");
312
+ var cache = /* @__PURE__ */ new Map();
313
+ async function getGitTimestamp(file) {
314
+ const cached = cache.get(file);
315
+ if (cached) return cached;
316
+ try {
317
+ const out = await (0, import_tinyexec.x)(
318
+ "git",
319
+ ["log", "-1", '--pretty="%ai"', import_node_path2.default.relative(process.cwd(), file)],
320
+ {
321
+ throwOnError: true
322
+ }
323
+ );
324
+ const time = new Date(out.stdout);
325
+ cache.set(file, time);
326
+ return time;
327
+ } catch {
328
+ return;
329
+ }
330
+ }
331
+
332
+ // src/loaders/mdx/build-mdx.ts
333
+ var import_mdx = require("@mdx-js/mdx");
334
+
335
+ // src/loaders/mdx/remark-include.ts
336
+ var import_unified = require("unified");
337
+ var import_unist_util_visit2 = require("unist-util-visit");
338
+ var path4 = __toESM(require("path"), 1);
339
+ var fs2 = __toESM(require("fs/promises"), 1);
340
+ var import_mdx_plugins = require("fumadocs-core/mdx-plugins");
341
+
342
+ // src/loaders/mdx/remark-unravel.ts
343
+ var import_unist_util_visit = require("unist-util-visit");
344
+ function remarkMarkAndUnravel() {
345
+ return (tree) => {
346
+ (0, import_unist_util_visit.visit)(tree, function(node, index, parent) {
347
+ let offset = -1;
348
+ let all = true;
349
+ let oneOrMore = false;
350
+ if (parent && typeof index === "number" && node.type === "paragraph") {
351
+ const children = node.children;
352
+ while (++offset < children.length) {
353
+ const child = children[offset];
354
+ if (child.type === "mdxJsxTextElement" || child.type === "mdxTextExpression") {
355
+ oneOrMore = true;
356
+ } else if (child.type === "text" && child.value.trim().length === 0) {
357
+ } else {
358
+ all = false;
359
+ break;
360
+ }
361
+ }
362
+ if (all && oneOrMore) {
363
+ offset = -1;
364
+ const newChildren = [];
365
+ while (++offset < children.length) {
366
+ const child = children[offset];
367
+ if (child.type === "mdxJsxTextElement") {
368
+ child.type = "mdxJsxFlowElement";
369
+ }
370
+ if (child.type === "mdxTextExpression") {
371
+ child.type = "mdxFlowExpression";
372
+ }
373
+ if (child.type === "text" && /^[\t\r\n ]+$/.test(String(child.value))) {
374
+ } else {
375
+ newChildren.push(child);
376
+ }
377
+ }
378
+ parent.children.splice(index, 1, ...newChildren);
379
+ return index;
380
+ }
381
+ }
382
+ });
383
+ };
384
+ }
385
+
386
+ // src/loaders/mdx/remark-include.ts
387
+ var ElementLikeTypes = [
388
+ "mdxJsxFlowElement",
389
+ "mdxJsxTextElement",
390
+ "containerDirective",
391
+ "textDirective",
392
+ "leafDirective"
393
+ ];
394
+ function isElementLike(node) {
395
+ return ElementLikeTypes.includes(node.type);
396
+ }
397
+ function parseElementAttributes(element) {
398
+ if (Array.isArray(element.attributes)) {
399
+ const attributes = {};
400
+ for (const attr of element.attributes) {
401
+ if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
402
+ attributes[attr.name] = attr.value;
403
+ }
404
+ }
405
+ return attributes;
406
+ }
407
+ return element.attributes ?? {};
408
+ }
409
+ function flattenNode(node) {
410
+ if ("children" in node)
411
+ return node.children.map((child) => flattenNode(child)).join("");
412
+ if ("value" in node) return node.value;
413
+ return "";
414
+ }
415
+ function parseSpecifier(specifier) {
416
+ const idx = specifier.lastIndexOf("#");
417
+ if (idx === -1) return { file: specifier };
418
+ return {
419
+ file: specifier.slice(0, idx),
420
+ section: specifier.slice(idx + 1)
421
+ };
422
+ }
423
+ function extractSection(root, section) {
424
+ let nodes;
425
+ let capturingHeadingContent = false;
426
+ (0, import_unist_util_visit2.visit)(root, (node) => {
427
+ if (node.type === "heading") {
428
+ if (capturingHeadingContent) {
429
+ return false;
430
+ }
431
+ if (node.data?.hProperties?.id === section) {
432
+ capturingHeadingContent = true;
433
+ nodes = [node];
434
+ return "skip";
435
+ }
436
+ return;
437
+ }
438
+ if (capturingHeadingContent) {
439
+ nodes?.push(node);
440
+ return "skip";
441
+ }
442
+ if (isElementLike(node) && node.name === "section") {
443
+ const attributes = parseElementAttributes(node);
444
+ if (attributes.id === section) {
445
+ nodes = node.children;
446
+ return false;
447
+ }
448
+ }
449
+ });
450
+ if (nodes)
451
+ return {
452
+ type: "root",
453
+ children: nodes
454
+ };
455
+ }
456
+ function remarkInclude() {
457
+ const TagName = "include";
458
+ const embedContent = async (file, heading, params, data) => {
459
+ let content;
460
+ try {
461
+ content = (await fs2.readFile(file)).toString();
462
+ } catch (e) {
463
+ throw new Error(
464
+ `failed to read file ${file}
465
+ ${e instanceof Error ? e.message : String(e)}`,
466
+ { cause: e }
467
+ );
468
+ }
469
+ const ext = path4.extname(file);
470
+ data._compiler?.addDependency(file);
471
+ if (params.lang || ext !== ".md" && ext !== ".mdx") {
472
+ const lang = params.lang ?? ext.slice(1);
473
+ return {
474
+ type: "code",
475
+ lang,
476
+ meta: params.meta,
477
+ value: content,
478
+ data: {}
479
+ };
480
+ }
481
+ const parser = data._getProcessor ? data._getProcessor(ext === ".mdx" ? "mdx" : "md") : this;
482
+ const parsed = fumaMatter(content);
483
+ let mdast = parser.parse({
484
+ path: file,
485
+ value: parsed.content,
486
+ data: { frontmatter: parsed.data }
487
+ });
488
+ const baseProcessor = (0, import_unified.unified)().use(remarkMarkAndUnravel);
489
+ if (heading) {
490
+ const extracted = extractSection(
491
+ await baseProcessor.use(import_mdx_plugins.remarkHeading).run(mdast),
492
+ heading
493
+ );
494
+ if (!extracted)
495
+ throw new Error(
496
+ `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.`
497
+ );
498
+ mdast = extracted;
499
+ } else {
500
+ mdast = await baseProcessor.run(mdast);
501
+ }
502
+ await update(mdast, path4.dirname(file), data);
503
+ return mdast;
504
+ };
505
+ async function update(tree, directory, data) {
506
+ const queue = [];
507
+ (0, import_unist_util_visit2.visit)(tree, ElementLikeTypes, (_node, _, parent) => {
508
+ const node = _node;
509
+ if (node.name !== TagName) return;
510
+ const specifier = flattenNode(node);
511
+ if (specifier.length === 0) return "skip";
512
+ const attributes = parseElementAttributes(node);
513
+ const { file: relativePath, section } = parseSpecifier(specifier);
514
+ const file = path4.resolve(
515
+ "cwd" in attributes ? process.cwd() : directory,
516
+ relativePath
517
+ );
518
+ queue.push(
519
+ embedContent(file, section, attributes, data).then((replace) => {
520
+ Object.assign(
521
+ parent && parent.type === "paragraph" ? parent : node,
522
+ replace
523
+ );
524
+ })
525
+ );
526
+ return "skip";
527
+ });
528
+ await Promise.all(queue);
529
+ }
530
+ return async (tree, file) => {
531
+ await update(tree, path4.dirname(file.path), file.data);
532
+ };
533
+ }
534
+
535
+ // src/loaders/mdx/remark-postprocess.ts
536
+ var import_unist_util_visit3 = require("unist-util-visit");
537
+ var import_mdast_util_to_markdown = require("mdast-util-to-markdown");
538
+ var import_estree_util_value_to_estree = require("estree-util-value-to-estree");
539
+ var import_unist_util_remove_position = require("unist-util-remove-position");
540
+ var import_remark_mdx = __toESM(require("remark-mdx"), 1);
541
+ function remarkPostprocess({
542
+ _format,
543
+ includeProcessedMarkdown = false,
544
+ includeMDAST = false,
545
+ valueToExport = []
546
+ }) {
547
+ let _stringifyProcessor;
548
+ const getStringifyProcessor = () => {
549
+ if (_format === "mdx") return this;
550
+ return _stringifyProcessor ??= this().use(import_remark_mdx.default).freeze();
551
+ };
552
+ return (tree, file) => {
553
+ let title;
554
+ const urls = [];
555
+ (0, import_unist_util_visit3.visit)(tree, ["heading", "link"], (node) => {
556
+ if (node.type === "heading" && node.depth === 1) {
557
+ title = flattenNode2(node);
558
+ }
559
+ if (node.type !== "link") return;
560
+ urls.push({
561
+ href: node.url
562
+ });
563
+ return "skip";
564
+ });
565
+ if (title) {
566
+ file.data.frontmatter ??= {};
567
+ if (!file.data.frontmatter.title) file.data.frontmatter.title = title;
568
+ }
569
+ file.data.extractedReferences = urls;
570
+ if (includeProcessedMarkdown) {
571
+ const processor = getStringifyProcessor();
572
+ file.data._markdown = (0, import_mdast_util_to_markdown.toMarkdown)(tree, {
573
+ ...processor.data("settings"),
574
+ // from https://github.com/remarkjs/remark/blob/main/packages/remark-stringify/lib/index.js
575
+ extensions: processor.data("toMarkdownExtensions") || []
576
+ });
577
+ }
578
+ if (includeMDAST) {
579
+ const options = includeMDAST === true ? {} : includeMDAST;
580
+ file.data._mdast = JSON.stringify(
581
+ options.removePosition ? (0, import_unist_util_remove_position.removePosition)(structuredClone(tree)) : tree
582
+ );
583
+ }
584
+ for (const { name, value } of file.data["mdx-export"] ?? []) {
585
+ tree.children.unshift(getMdastExport(name, value));
586
+ }
587
+ for (const name of valueToExport) {
588
+ if (!(name in file.data)) continue;
589
+ tree.children.unshift(getMdastExport(name, file.data[name]));
590
+ }
591
+ };
592
+ }
593
+ function getMdastExport(name, value) {
594
+ return {
595
+ type: "mdxjsEsm",
596
+ value: "",
597
+ data: {
598
+ estree: {
599
+ type: "Program",
600
+ sourceType: "module",
601
+ body: [
602
+ {
603
+ type: "ExportNamedDeclaration",
604
+ attributes: [],
605
+ specifiers: [],
606
+ source: null,
607
+ declaration: {
608
+ type: "VariableDeclaration",
609
+ kind: "let",
610
+ declarations: [
611
+ {
612
+ type: "VariableDeclarator",
613
+ id: {
614
+ type: "Identifier",
615
+ name
616
+ },
617
+ init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
618
+ }
619
+ ]
620
+ }
621
+ }
622
+ ]
623
+ }
624
+ }
625
+ };
626
+ }
627
+ function flattenNode2(node) {
628
+ if ("children" in node)
629
+ return node.children.map((child) => flattenNode2(child)).join("");
630
+ if ("value" in node) return node.value;
631
+ return "";
632
+ }
633
+
634
+ // src/loaders/mdx/build-mdx.ts
635
+ var cache2 = /* @__PURE__ */ new Map();
636
+ async function buildMDX(cacheKey, source, options) {
637
+ const { filePath, frontmatter, data, _compiler, ...rest } = options;
638
+ function getProcessor(format) {
639
+ const key = `${cacheKey}:${format}`;
640
+ let processor = cache2.get(key);
641
+ if (!processor) {
642
+ processor = (0, import_mdx.createProcessor)({
643
+ outputFormat: "program",
644
+ ...rest,
645
+ remarkPlugins: [
646
+ remarkInclude,
647
+ ...rest.remarkPlugins ?? [],
648
+ [
649
+ remarkPostprocess,
650
+ {
651
+ _format: format,
652
+ ...options.postprocess,
653
+ valueToExport: [
654
+ ...options.postprocess?.valueToExport ?? [],
655
+ "structuredData",
656
+ "extractedReferences",
657
+ "frontmatter",
658
+ "lastModified",
659
+ "_markdown",
660
+ "_mdast"
661
+ ]
662
+ }
663
+ ]
664
+ ],
665
+ format
666
+ });
667
+ cache2.set(key, processor);
668
+ }
669
+ return processor;
670
+ }
671
+ return getProcessor(
672
+ options.format ?? (filePath.endsWith(".mdx") ? "mdx" : "md")
673
+ ).process({
674
+ value: source,
675
+ path: filePath,
676
+ data: {
677
+ ...data,
678
+ frontmatter,
679
+ _compiler,
680
+ _getProcessor: getProcessor
681
+ }
682
+ });
683
+ }
684
+
685
+ // src/loaders/mdx/index.ts
686
+ var import_zod = require("zod");
687
+ var import_promises2 = __toESM(require("fs/promises"), 1);
688
+ var import_node_path3 = __toESM(require("path"), 1);
689
+ var import_node_crypto = require("crypto");
690
+ var querySchema = import_zod.z.object({
691
+ only: import_zod.z.literal(["frontmatter", "all"]).default("all"),
692
+ collection: import_zod.z.string().optional()
693
+ }).loose();
694
+ var cacheEntry = import_zod.z.object({
695
+ code: import_zod.z.string(),
696
+ map: import_zod.z.any().optional(),
697
+ hash: import_zod.z.string().optional()
698
+ });
699
+ function createMdxLoader(configLoader) {
700
+ return async ({
701
+ source: value,
702
+ development: isDevelopment,
703
+ query,
704
+ compiler,
705
+ filePath
706
+ }) => {
707
+ const matter = fumaMatter(value);
708
+ const parsed = querySchema.parse(query);
709
+ const config = await configLoader.getConfig();
710
+ let after;
711
+ if (!isDevelopment && config.global.experimentalBuildCache) {
712
+ const cacheDir = config.global.experimentalBuildCache;
713
+ const cacheKey = `${parsed.hash}_${parsed.collection ?? "global"}_${generateCacheHash(filePath)}`;
714
+ const cached = await import_promises2.default.readFile(import_node_path3.default.join(cacheDir, cacheKey)).then((content) => cacheEntry.parse(JSON.parse(content.toString()))).catch(() => null);
715
+ if (cached && cached.hash === generateCacheHash(value)) return cached;
716
+ after = async () => {
717
+ await import_promises2.default.mkdir(cacheDir, { recursive: true });
718
+ await import_promises2.default.writeFile(
719
+ import_node_path3.default.join(cacheDir, cacheKey),
720
+ JSON.stringify({
721
+ ...out,
722
+ hash: generateCacheHash(value)
723
+ })
724
+ );
725
+ };
726
+ }
727
+ const collection = parsed.collection ? config.collections.get(parsed.collection) : void 0;
728
+ let docCollection;
729
+ switch (collection?.type) {
730
+ case "doc":
731
+ docCollection = collection;
732
+ break;
733
+ case "docs":
734
+ docCollection = collection.docs;
735
+ break;
736
+ }
737
+ if (docCollection?.schema) {
738
+ matter.data = await validate(
739
+ docCollection.schema,
740
+ matter.data,
741
+ {
742
+ source: value,
743
+ path: filePath
744
+ },
745
+ `invalid frontmatter in ${filePath}`
746
+ );
747
+ }
748
+ if (parsed.only === "frontmatter") {
749
+ return {
750
+ code: `export const frontmatter = ${JSON.stringify(matter.data)}`,
751
+ map: null
752
+ };
753
+ }
754
+ const data = {};
755
+ if (config.global.lastModifiedTime === "git") {
756
+ data.lastModified = (await getGitTimestamp(filePath))?.getTime();
757
+ }
758
+ const lineOffset = isDevelopment ? countLines(matter.matter) : 0;
759
+ const compiled = await buildMDX(
760
+ `${getConfigHash(config)}:${parsed.collection ?? "global"}`,
761
+ "\n".repeat(lineOffset) + matter.content,
762
+ {
763
+ development: isDevelopment,
764
+ ...docCollection?.mdxOptions ?? await config.getDefaultMDXOptions(),
765
+ postprocess: docCollection?.postprocess,
766
+ data,
767
+ filePath,
768
+ frontmatter: matter.data,
769
+ _compiler: compiler
770
+ }
771
+ );
772
+ const out = {
773
+ code: String(compiled.value),
774
+ map: compiled.map
775
+ };
776
+ await after?.();
777
+ return out;
778
+ };
779
+ }
780
+ var hashes = /* @__PURE__ */ new WeakMap();
781
+ function getConfigHash(config) {
782
+ let hash = hashes.get(config);
783
+ if (hash) return hash;
784
+ hash = Date.now().toString();
785
+ hashes.set(config, hash);
786
+ return hash;
787
+ }
788
+ function generateCacheHash(input) {
789
+ return (0, import_node_crypto.createHash)("md5").update(input).digest("hex");
790
+ }
791
+ function countLines(s) {
792
+ let num = 0;
793
+ for (const c of s) {
794
+ if (c === "\n") num++;
795
+ }
796
+ return num;
797
+ }
798
+
799
+ // src/loaders/adapter.ts
800
+ var import_node_url2 = require("url");
801
+ var import_promises3 = __toESM(require("fs/promises"), 1);
802
+ var import_node_querystring = require("querystring");
803
+ var import_node_path4 = __toESM(require("path"), 1);
804
+ function toNode(loader, filterByPath) {
805
+ return async (url, _context, nextLoad) => {
806
+ if (!url.startsWith("file:///")) return nextLoad(url);
807
+ const parsedUrl = new URL(url);
808
+ const filePath = (0, import_node_url2.fileURLToPath)(parsedUrl);
809
+ if (filterByPath(filePath)) {
810
+ const source = (await import_promises3.default.readFile(filePath)).toString();
811
+ const result = await loader({
812
+ filePath,
813
+ query: Object.fromEntries(parsedUrl.searchParams.entries()),
814
+ source,
815
+ development: false,
816
+ compiler: {
817
+ addDependency() {
818
+ }
819
+ }
820
+ });
821
+ return {
822
+ source: result.code,
823
+ format: "module",
824
+ shortCircuit: true
825
+ };
826
+ }
827
+ return nextLoad(url);
828
+ };
829
+ }
830
+
831
+ // src/core.ts
832
+ var import_node_path5 = __toESM(require("path"), 1);
833
+ var import_promises4 = __toESM(require("fs/promises"), 1);
834
+ function createCore(options, defaultPlugins = []) {
835
+ let config;
836
+ let plugins2;
837
+ return {
838
+ _options: options,
839
+ getPluginContext() {
840
+ return {
841
+ core: this,
842
+ ...options
843
+ };
844
+ },
845
+ /**
846
+ * Convenient cache store, reset when config changes
847
+ */
848
+ cache: /* @__PURE__ */ new Map(),
849
+ async init({ config: newConfig }) {
850
+ config = await newConfig;
851
+ this.cache.clear();
852
+ plugins2 = [];
853
+ for await (const option of [
854
+ ...defaultPlugins,
855
+ ...config.global.plugins ?? []
856
+ ]) {
857
+ if (!option) continue;
858
+ if (Array.isArray(option)) plugins2.push(...option);
859
+ else plugins2.push(option);
860
+ }
861
+ for (const plugin of plugins2) {
862
+ const out = await plugin.config?.call(this.getPluginContext(), config);
863
+ if (out) config = out;
864
+ }
865
+ return this;
866
+ },
867
+ getConfig() {
868
+ return config;
869
+ },
870
+ creatConfigLoader() {
871
+ return {
872
+ getConfig() {
873
+ return config;
874
+ }
875
+ };
876
+ },
877
+ async initServer(server) {
878
+ for (const plugin of plugins2) {
879
+ await plugin.configureServer?.call(this.getPluginContext(), server);
880
+ }
881
+ },
882
+ async emitAndWrite({
883
+ filterPlugin = () => true
884
+ } = {}) {
885
+ const start = performance.now();
886
+ const out = await Promise.all(
887
+ plugins2.map((plugin) => {
888
+ if (!filterPlugin(plugin) || !plugin.emit) return [];
889
+ return plugin.emit.call(this.getPluginContext());
890
+ })
891
+ );
892
+ await Promise.all(
893
+ out.flat().map(async (entry) => {
894
+ const file = import_node_path5.default.join(options.outDir, entry.path);
895
+ await import_promises4.default.mkdir(import_node_path5.default.dirname(file), { recursive: true });
896
+ await import_promises4.default.writeFile(file, entry.content);
897
+ })
898
+ );
899
+ console.log(`[MDX] generated files in ${performance.now() - start}ms`);
900
+ }
901
+ };
902
+ }
903
+
904
+ // src/node/loader.ts
905
+ var core = createCore({
906
+ environment: "node",
907
+ configPath: findConfigFile(),
908
+ outDir: ".source"
909
+ });
910
+ var load2 = toNode(
911
+ createMdxLoader(
912
+ staticConfig({
913
+ core,
914
+ buildConfig: true
915
+ })
916
+ ),
917
+ (filePath) => filePath.endsWith(".md") || filePath.endsWith(".mdx")
918
+ );
919
+ // Annotate the CommonJS export names for ESM import in node:
920
+ 0 && (module.exports = {
921
+ load
922
+ });