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
@@ -1,527 +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/mdx-plugins/remark-exports.ts
34
- function remarkMdxExport({ values }) {
35
- return (tree, vfile) => {
36
- for (const name of values) {
37
- if (!(name in vfile.data)) return;
38
- tree.children.unshift(getMdastExport(name, vfile.data[name]));
39
- }
40
- };
41
- }
42
- function getMdastExport(name, value) {
43
- return {
44
- type: "mdxjsEsm",
45
- value: "",
46
- data: {
47
- estree: {
48
- type: "Program",
49
- sourceType: "module",
50
- body: [
51
- {
52
- type: "ExportNamedDeclaration",
53
- specifiers: [],
54
- source: null,
55
- declaration: {
56
- type: "VariableDeclaration",
57
- kind: "let",
58
- declarations: [
59
- {
60
- type: "VariableDeclarator",
61
- id: {
62
- type: "Identifier",
63
- name
64
- },
65
- init: (0, import_estree_util_value_to_estree.valueToEstree)(value)
66
- }
67
- ]
68
- }
69
- }
70
- ]
71
- }
72
- }
73
- };
74
- }
75
- var import_estree_util_value_to_estree;
76
- var init_remark_exports = __esm({
77
- "src/mdx-plugins/remark-exports.ts"() {
78
- "use strict";
79
- import_estree_util_value_to_estree = require("estree-util-value-to-estree");
80
- }
81
- });
82
-
83
- // src/utils/mdx-options.ts
84
- var mdx_options_exports = {};
85
- __export(mdx_options_exports, {
86
- getDefaultMDXOptions: () => getDefaultMDXOptions
87
- });
88
- function pluginOption(def, options = []) {
89
- const list = def(Array.isArray(options) ? options : []).filter(
90
- Boolean
91
- );
92
- if (typeof options === "function") {
93
- return options(list);
94
- }
95
- return list;
96
- }
97
- function getDefaultMDXOptions({
98
- valueToExport = [],
99
- rehypeCodeOptions,
100
- remarkImageOptions,
101
- remarkHeadingOptions,
102
- remarkStructureOptions,
103
- remarkCodeTabOptions,
104
- ...mdxOptions
105
- }) {
106
- const mdxExports = [
107
- "structuredData",
108
- "frontmatter",
109
- "lastModified",
110
- ...valueToExport
111
- ];
112
- const remarkPlugins = pluginOption(
113
- (v) => [
114
- plugins.remarkGfm,
115
- [
116
- plugins.remarkHeading,
117
- {
118
- generateToc: false,
119
- ...remarkHeadingOptions
120
- }
121
- ],
122
- remarkImageOptions !== false && [plugins.remarkImage, remarkImageOptions],
123
- // Fumadocs 14 compatibility
124
- "remarkCodeTab" in plugins && remarkCodeTabOptions !== false && plugins.remarkCodeTab,
125
- ...v,
126
- remarkStructureOptions !== false && [
127
- plugins.remarkStructure,
128
- remarkStructureOptions
129
- ],
130
- [remarkMdxExport, { values: mdxExports }]
131
- ],
132
- mdxOptions.remarkPlugins
133
- );
134
- const rehypePlugins = pluginOption(
135
- (v) => [
136
- rehypeCodeOptions !== false && [plugins.rehypeCode, rehypeCodeOptions],
137
- ...v,
138
- [plugins.rehypeToc]
139
- ],
140
- mdxOptions.rehypePlugins
141
- );
142
- return {
143
- ...mdxOptions,
144
- remarkPlugins,
145
- rehypePlugins
146
- };
147
- }
148
- var plugins;
149
- var init_mdx_options = __esm({
150
- "src/utils/mdx-options.ts"() {
151
- "use strict";
152
- plugins = __toESM(require("fumadocs-core/mdx-plugins"), 1);
153
- init_remark_exports();
154
- }
155
- });
156
-
157
- // src/loader-mdx.ts
158
- var loader_mdx_exports = {};
159
- __export(loader_mdx_exports, {
160
- default: () => loader
161
- });
162
- module.exports = __toCommonJS(loader_mdx_exports);
163
- var path4 = __toESM(require("path"), 1);
164
- var import_node_querystring = require("querystring");
165
- var import_gray_matter2 = __toESM(require("gray-matter"), 1);
166
-
167
- // src/utils/config.ts
168
- var fs = __toESM(require("fs/promises"), 1);
169
- var path = __toESM(require("path"), 1);
170
- var import_node_url = require("url");
171
-
172
- // src/config/build.ts
173
- function buildConfig(config) {
174
- const collections = /* @__PURE__ */ new Map();
175
- let globalConfig;
176
- for (const [k, v] of Object.entries(config)) {
177
- if (!v) {
178
- continue;
179
- }
180
- if (typeof v === "object" && "type" in v) {
181
- if (v.type === "docs") {
182
- collections.set(k, v);
183
- continue;
184
- }
185
- if (v.type === "doc" || v.type === "meta") {
186
- collections.set(k, v);
187
- continue;
188
- }
189
- }
190
- if (k === "default") {
191
- globalConfig = v;
192
- continue;
193
- }
194
- return [
195
- `Unknown export "${k}", you can only export collections from source configuration file.`,
196
- null
197
- ];
198
- }
199
- return [
200
- null,
201
- {
202
- global: globalConfig,
203
- collections
204
- }
205
- ];
206
- }
207
-
208
- // src/utils/config.ts
209
- var cache = null;
210
- async function compileConfig(configPath, outDir) {
211
- const { build } = await import("esbuild");
212
- const transformed = await build({
213
- entryPoints: [{ in: configPath, out: "source.config" }],
214
- bundle: true,
215
- outdir: outDir,
216
- target: "node18",
217
- write: true,
218
- platform: "node",
219
- format: "esm",
220
- packages: "external",
221
- outExtension: {
222
- ".js": ".mjs"
223
- },
224
- allowOverwrite: true
225
- });
226
- if (transformed.errors.length > 0) {
227
- throw new Error("failed to compile configuration file");
228
- }
229
- }
230
- async function loadConfig(configPath, hash, build = false) {
231
- if (cache && cache.hash === hash) {
232
- return await cache.config;
233
- }
234
- if (build) await compileConfig(configPath, ".source");
235
- const url = (0, import_node_url.pathToFileURL)(path.resolve(".source/source.config.mjs"));
236
- const config = import(`${url.href}?hash=${hash}`).then((loaded) => {
237
- const [err, config2] = buildConfig(
238
- // every call to `loadConfig` will cause the previous cache to be ignored
239
- loaded
240
- );
241
- if (err !== null) throw new Error(err);
242
- return config2;
243
- });
244
- cache = { config, hash };
245
- return await config;
246
- }
247
- async function getConfigHash(configPath) {
248
- const stats = await fs.stat(configPath).catch(() => void 0);
249
- if (stats) {
250
- return stats.mtime.getTime().toString();
251
- }
252
- throw new Error("Cannot find config file");
253
- }
254
-
255
- // src/utils/build-mdx.ts
256
- var import_mdx = require("@mdx-js/mdx");
257
-
258
- // src/mdx-plugins/remark-include.ts
259
- var import_unist_util_visit = require("unist-util-visit");
260
- var path2 = __toESM(require("path"), 1);
261
- var fs2 = __toESM(require("fs/promises"), 1);
262
- var import_gray_matter = __toESM(require("gray-matter"), 1);
263
- function flattenNode(node) {
264
- if ("children" in node)
265
- return node.children.map((child) => flattenNode(child)).join("");
266
- if ("value" in node) return node.value;
267
- return "";
268
- }
269
- function remarkInclude() {
270
- const TagName = "include";
271
- async function update(tree, file, processor, compiler) {
272
- const queue = [];
273
- (0, import_unist_util_visit.visit)(
274
- tree,
275
- ["mdxJsxFlowElement", "mdxJsxTextElement"],
276
- (node, _, parent) => {
277
- let specifier;
278
- const params = {};
279
- if ((node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") && node.name === TagName) {
280
- const value = flattenNode(node);
281
- if (value.length > 0) {
282
- for (const attr of node.attributes) {
283
- if (attr.type === "mdxJsxAttribute" && (typeof attr.value === "string" || attr.value === null)) {
284
- params[attr.name] = attr.value;
285
- }
286
- }
287
- specifier = value;
288
- }
289
- }
290
- if (!specifier) return;
291
- const targetPath = path2.resolve(
292
- "cwd" in params ? process.cwd() : path2.dirname(file),
293
- specifier
294
- );
295
- const asCode = params.lang || !specifier.endsWith(".md") && !specifier.endsWith(".mdx");
296
- queue.push(
297
- fs2.readFile(targetPath).then(async (content) => {
298
- compiler?.addDependency(targetPath);
299
- if (asCode) {
300
- const lang = params.lang ?? path2.extname(specifier).slice(1);
301
- Object.assign(node, {
302
- type: "code",
303
- lang,
304
- meta: params.meta,
305
- value: content.toString(),
306
- data: {}
307
- });
308
- return;
309
- }
310
- const parsed = processor.parse((0, import_gray_matter.default)(content).content);
311
- await update(parsed, targetPath, processor, compiler);
312
- Object.assign(
313
- parent && parent.type === "paragraph" ? parent : node,
314
- parsed
315
- );
316
- }).catch((e) => {
317
- console.warn(`failed to read file: ${targetPath}`, e);
318
- })
319
- );
320
- return "skip";
321
- }
322
- );
323
- await Promise.all(queue);
324
- }
325
- return async (tree, file) => {
326
- await update(tree, file.path, this, file.data._compiler);
327
- };
328
- }
329
-
330
- // src/utils/build-mdx.ts
331
- var cache2 = /* @__PURE__ */ new Map();
332
- async function buildMDX(cacheKey, source, options = {}) {
333
- const { filePath, frontmatter, data, ...rest } = options;
334
- let format = options.format;
335
- if (!format && filePath) {
336
- format = filePath.endsWith(".mdx") ? "mdx" : "md";
337
- }
338
- format ??= "mdx";
339
- const key = `${cacheKey}:${format}`;
340
- let cached = cache2.get(key);
341
- if (cached === void 0) {
342
- cached = (0, import_mdx.createProcessor)({
343
- outputFormat: "program",
344
- development: process.env.NODE_ENV === "development",
345
- ...rest,
346
- remarkPlugins: [remarkInclude, ...rest.remarkPlugins ?? []],
347
- format
348
- });
349
- cache2.set(key, cached);
350
- }
351
- return cached.process({
352
- value: source,
353
- path: filePath,
354
- data: {
355
- ...data,
356
- frontmatter,
357
- _compiler: options._compiler
358
- }
359
- });
360
- }
361
-
362
- // src/utils/git-timestamp.ts
363
- var import_node_path = __toESM(require("path"), 1);
364
- var import_node_fs = __toESM(require("fs"), 1);
365
- var import_cross_spawn = require("cross-spawn");
366
- var cache3 = /* @__PURE__ */ new Map();
367
- function getGitTimestamp(file) {
368
- const cachedTimestamp = cache3.get(file);
369
- if (cachedTimestamp) return Promise.resolve(cachedTimestamp);
370
- return new Promise((resolve3, reject) => {
371
- const cwd = import_node_path.default.dirname(file);
372
- if (!import_node_fs.default.existsSync(cwd)) {
373
- resolve3(void 0);
374
- return;
375
- }
376
- const fileName = import_node_path.default.basename(file);
377
- const child = (0, import_cross_spawn.spawn)("git", ["log", "-1", '--pretty="%ai"', fileName], {
378
- cwd
379
- });
380
- let output;
381
- child.stdout.on("data", (d) => output = new Date(String(d)));
382
- child.on("close", () => {
383
- if (output) cache3.set(file, output);
384
- resolve3(output);
385
- });
386
- child.on("error", reject);
387
- });
388
- }
389
-
390
- // src/utils/schema.ts
391
- var import_zod = require("zod");
392
- var import_picocolors = __toESM(require("picocolors"), 1);
393
- var metaSchema = import_zod.z.object({
394
- title: import_zod.z.string().optional(),
395
- pages: import_zod.z.array(import_zod.z.string()).optional(),
396
- description: import_zod.z.string().optional(),
397
- root: import_zod.z.boolean().optional(),
398
- defaultOpen: import_zod.z.boolean().optional(),
399
- icon: import_zod.z.string().optional()
400
- });
401
- var frontmatterSchema = import_zod.z.object({
402
- title: import_zod.z.string(),
403
- description: import_zod.z.string().optional(),
404
- icon: import_zod.z.string().optional(),
405
- full: import_zod.z.boolean().optional(),
406
- // Fumadocs OpenAPI generated
407
- _openapi: import_zod.z.object({}).passthrough().optional()
408
- });
409
- var ValidationError = class extends Error {
410
- constructor(message, issues) {
411
- super(message);
412
- this.issues = issues;
413
- }
414
- print() {
415
- console.error(
416
- [
417
- `[MDX] ${this.message}:`,
418
- ...this.issues.map(
419
- (issue) => import_picocolors.default.redBright(
420
- `- ${import_picocolors.default.bold(issue.path?.join(".") ?? "*")}: ${issue.message}`
421
- )
422
- )
423
- ].join("\n")
424
- );
425
- }
426
- toString() {
427
- return `${this.message}:
428
- ${this.issues.map((issue) => ` ${issue.path}: ${issue.message}`).join("\n")}`;
429
- }
430
- };
431
- async function validate(schema, data, context, errorMessage) {
432
- if (typeof schema === "function" && !("~standard" in schema)) {
433
- schema = schema(context);
434
- }
435
- if ("~standard" in schema) {
436
- const result = await schema["~standard"].validate(
437
- data
438
- );
439
- if (result.issues) {
440
- throw new ValidationError(errorMessage, result.issues);
441
- }
442
- return result.value;
443
- }
444
- return data;
445
- }
446
-
447
- // src/loader-mdx.ts
448
- function parseQuery(query) {
449
- let collection;
450
- let hash;
451
- const parsed = (0, import_node_querystring.parse)(query.slice(1));
452
- if (parsed.collection && typeof parsed.collection === "string")
453
- collection = parsed.collection;
454
- if (parsed.hash && typeof parsed.hash === "string") hash = parsed.hash;
455
- return { collection, hash };
456
- }
457
- async function loader(source, callback) {
458
- this.cacheable(true);
459
- const context = this.context;
460
- const filePath = this.resourcePath;
461
- const { _ctx } = this.getOptions();
462
- const matter2 = (0, import_gray_matter2.default)(source);
463
- const {
464
- hash: configHash = await getConfigHash(_ctx.configPath),
465
- collection: collectionId
466
- } = parseQuery(this.resourceQuery);
467
- const config = await loadConfig(_ctx.configPath, configHash);
468
- let collection = collectionId !== void 0 ? config.collections.get(collectionId) : void 0;
469
- if (collection && collection.type === "docs") collection = collection.docs;
470
- if (collection && collection.type !== "doc") {
471
- collection = void 0;
472
- }
473
- let mdxOptions = collection?.mdxOptions;
474
- if (!mdxOptions) {
475
- const { getDefaultMDXOptions: getDefaultMDXOptions2 } = await Promise.resolve().then(() => (init_mdx_options(), mdx_options_exports));
476
- config._mdx_loader ??= {};
477
- const extendedOptions = config.global?.mdxOptions;
478
- config._mdx_loader.cachedProcessorOptions ??= typeof extendedOptions === "function" ? getDefaultMDXOptions2(await extendedOptions()) : getDefaultMDXOptions2(extendedOptions ?? {});
479
- mdxOptions = config._mdx_loader.cachedProcessorOptions;
480
- }
481
- if (collection?.schema) {
482
- matter2.data = await validate(
483
- collection.schema,
484
- matter2.data,
485
- {
486
- source,
487
- path: filePath
488
- },
489
- `invalid frontmatter in ${filePath}`
490
- );
491
- }
492
- let timestamp;
493
- if (config.global?.lastModifiedTime === "git")
494
- timestamp = (await getGitTimestamp(filePath))?.getTime();
495
- try {
496
- const lineOffset = "\n".repeat(
497
- this.mode === "development" ? lines(source) - lines(matter2.content) : 0
498
- );
499
- const file = await buildMDX(
500
- `${configHash}:${collectionId ?? "global"}`,
501
- lineOffset + matter2.content,
502
- {
503
- development: this.mode === "development",
504
- ...mdxOptions,
505
- filePath,
506
- frontmatter: matter2.data,
507
- data: {
508
- lastModified: timestamp
509
- },
510
- _compiler: this
511
- }
512
- );
513
- callback(void 0, String(file.value), file.map ?? void 0);
514
- } catch (error) {
515
- if (!(error instanceof Error)) throw error;
516
- const fpath = path4.relative(context, filePath);
517
- error.message = `${fpath}:${error.name}: ${error.message}`;
518
- callback(error);
519
- }
520
- }
521
- function lines(s) {
522
- let num = 0;
523
- for (const c of s) {
524
- if (c === "\n") num++;
525
- }
526
- return num;
527
- }
@@ -1,162 +0,0 @@
1
- import {
2
- getConfigHash,
3
- loadConfig
4
- } from "./chunk-HFLDWPJA.js";
5
- import "./chunk-DRVUBK5B.js";
6
- import {
7
- validate
8
- } from "./chunk-2ZOW45YZ.js";
9
- import {
10
- remarkInclude
11
- } from "./chunk-MK7EXW7O.js";
12
-
13
- // src/loader-mdx.ts
14
- import * as path2 from "node:path";
15
- import { parse } from "node:querystring";
16
- import grayMatter from "gray-matter";
17
-
18
- // src/utils/build-mdx.ts
19
- import { createProcessor } from "@mdx-js/mdx";
20
- var cache = /* @__PURE__ */ new Map();
21
- async function buildMDX(cacheKey, source, options = {}) {
22
- const { filePath, frontmatter, data, ...rest } = options;
23
- let format = options.format;
24
- if (!format && filePath) {
25
- format = filePath.endsWith(".mdx") ? "mdx" : "md";
26
- }
27
- format ??= "mdx";
28
- const key = `${cacheKey}:${format}`;
29
- let cached = cache.get(key);
30
- if (cached === void 0) {
31
- cached = createProcessor({
32
- outputFormat: "program",
33
- development: process.env.NODE_ENV === "development",
34
- ...rest,
35
- remarkPlugins: [remarkInclude, ...rest.remarkPlugins ?? []],
36
- format
37
- });
38
- cache.set(key, cached);
39
- }
40
- return cached.process({
41
- value: source,
42
- path: filePath,
43
- data: {
44
- ...data,
45
- frontmatter,
46
- _compiler: options._compiler
47
- }
48
- });
49
- }
50
-
51
- // src/utils/git-timestamp.ts
52
- import path from "node:path";
53
- import fs from "node:fs";
54
- import { spawn } from "cross-spawn";
55
- var cache2 = /* @__PURE__ */ new Map();
56
- function getGitTimestamp(file) {
57
- const cachedTimestamp = cache2.get(file);
58
- if (cachedTimestamp) return Promise.resolve(cachedTimestamp);
59
- return new Promise((resolve, reject) => {
60
- const cwd = path.dirname(file);
61
- if (!fs.existsSync(cwd)) {
62
- resolve(void 0);
63
- return;
64
- }
65
- const fileName = path.basename(file);
66
- const child = spawn("git", ["log", "-1", '--pretty="%ai"', fileName], {
67
- cwd
68
- });
69
- let output;
70
- child.stdout.on("data", (d) => output = new Date(String(d)));
71
- child.on("close", () => {
72
- if (output) cache2.set(file, output);
73
- resolve(output);
74
- });
75
- child.on("error", reject);
76
- });
77
- }
78
-
79
- // src/loader-mdx.ts
80
- function parseQuery(query) {
81
- let collection;
82
- let hash;
83
- const parsed = parse(query.slice(1));
84
- if (parsed.collection && typeof parsed.collection === "string")
85
- collection = parsed.collection;
86
- if (parsed.hash && typeof parsed.hash === "string") hash = parsed.hash;
87
- return { collection, hash };
88
- }
89
- async function loader(source, callback) {
90
- this.cacheable(true);
91
- const context = this.context;
92
- const filePath = this.resourcePath;
93
- const { _ctx } = this.getOptions();
94
- const matter = grayMatter(source);
95
- const {
96
- hash: configHash = await getConfigHash(_ctx.configPath),
97
- collection: collectionId
98
- } = parseQuery(this.resourceQuery);
99
- const config = await loadConfig(_ctx.configPath, configHash);
100
- let collection = collectionId !== void 0 ? config.collections.get(collectionId) : void 0;
101
- if (collection && collection.type === "docs") collection = collection.docs;
102
- if (collection && collection.type !== "doc") {
103
- collection = void 0;
104
- }
105
- let mdxOptions = collection?.mdxOptions;
106
- if (!mdxOptions) {
107
- const { getDefaultMDXOptions } = await import("./mdx-options-CAU273O3.js");
108
- config._mdx_loader ??= {};
109
- const extendedOptions = config.global?.mdxOptions;
110
- config._mdx_loader.cachedProcessorOptions ??= typeof extendedOptions === "function" ? getDefaultMDXOptions(await extendedOptions()) : getDefaultMDXOptions(extendedOptions ?? {});
111
- mdxOptions = config._mdx_loader.cachedProcessorOptions;
112
- }
113
- if (collection?.schema) {
114
- matter.data = await validate(
115
- collection.schema,
116
- matter.data,
117
- {
118
- source,
119
- path: filePath
120
- },
121
- `invalid frontmatter in ${filePath}`
122
- );
123
- }
124
- let timestamp;
125
- if (config.global?.lastModifiedTime === "git")
126
- timestamp = (await getGitTimestamp(filePath))?.getTime();
127
- try {
128
- const lineOffset = "\n".repeat(
129
- this.mode === "development" ? lines(source) - lines(matter.content) : 0
130
- );
131
- const file = await buildMDX(
132
- `${configHash}:${collectionId ?? "global"}`,
133
- lineOffset + matter.content,
134
- {
135
- development: this.mode === "development",
136
- ...mdxOptions,
137
- filePath,
138
- frontmatter: matter.data,
139
- data: {
140
- lastModified: timestamp
141
- },
142
- _compiler: this
143
- }
144
- );
145
- callback(void 0, String(file.value), file.map ?? void 0);
146
- } catch (error) {
147
- if (!(error instanceof Error)) throw error;
148
- const fpath = path2.relative(context, filePath);
149
- error.message = `${fpath}:${error.name}: ${error.message}`;
150
- callback(error);
151
- }
152
- }
153
- function lines(s) {
154
- let num = 0;
155
- for (const c of s) {
156
- if (c === "\n") num++;
157
- }
158
- return num;
159
- }
160
- export {
161
- loader as default
162
- };