@heikeson/md-engine 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,855 @@
1
+ import { mdxComponents, isSafeHref } from './chunk-QDDS7MPU.js';
2
+ import { asciiAlpha, asciiAlphanumeric, markdownLineEnding } from 'micromark-util-character';
3
+ import { fromMarkdown } from 'mdast-util-from-markdown';
4
+ import { gfm } from 'micromark-extension-gfm';
5
+ import { gfmFromMarkdown } from 'mdast-util-gfm';
6
+ import { math } from 'micromark-extension-math';
7
+ import { mathFromMarkdown } from 'mdast-util-math';
8
+ import { useMemo } from 'react';
9
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
10
+ import { unified } from 'unified';
11
+ import remarkParse from 'remark-parse';
12
+ import remarkGfm from 'remark-gfm';
13
+ import remarkMath from 'remark-math';
14
+ import remarkRehype from 'remark-rehype';
15
+ import rehypeSlug from 'rehype-slug';
16
+ import rehypeKatex from 'rehype-katex';
17
+ import { toJsxRuntime } from 'hast-util-to-jsx-runtime';
18
+ import { visit } from 'unist-util-visit';
19
+
20
+ // src/registry.ts
21
+ var MAX_CONTAINER_DEPTH = 3;
22
+ var ITEMS = {
23
+ Tab: { name: "Tab", attrs: ["value"], boolAttrs: ["default"] },
24
+ Step: { name: "Step", attrs: ["title"] },
25
+ // 允许自闭合:fumadocs 风格 `<Card title="…" description="…" />`(描述写在属性里)
26
+ Card: { name: "Card", attrs: ["title", "href", "icon", "description"], selfClosing: true },
27
+ // type: open / close —— 控制默认展开还是收起
28
+ AccItem: { name: "AccItem", attrs: ["title", "type"] },
29
+ // 文件树目录:可嵌套,defaultOpen 布尔控制默认展开
30
+ Folder: { name: "Folder", attrs: ["name"], boolAttrs: ["defaultOpen"] },
31
+ // 文件树叶子:自闭合,href 可选(给了就渲染成链接);icon 可选(覆盖自动类型图标)
32
+ File: { name: "File", attrs: ["name", "href", "icon"], selfClosing: true },
33
+ // 类型表行:name 属性名、type 类型、default 默认值、required 布尔必填
34
+ TypeItem: { name: "TypeItem", attrs: ["name", "type", "default"], boolAttrs: ["required"] }
35
+ };
36
+ var COMPONENTS = {
37
+ Callout: {
38
+ name: "Callout",
39
+ mode: "visual",
40
+ // icon:自定义图标,字符串(emoji / 短文本);不写则用类型默认图标
41
+ attrs: ["type", "title", "icon"],
42
+ defaultAttrs: { type: "note" }
43
+ },
44
+ Tabs: { name: "Tabs", mode: "visual", items: "Tab" },
45
+ Steps: { name: "Steps", mode: "visual", items: "Step" },
46
+ Cards: { name: "Cards", mode: "visual", items: "Card" },
47
+ Accordion: { name: "Accordion", mode: "visual", items: "AccItem" },
48
+ // 文件树容器:子项可混用 Folder / File
49
+ Files: { name: "Files", mode: "visual", items: ["Folder", "File"] },
50
+ // 类型表:fumadocs 的 TypeTable,但属性只支持字符串,故用子项而非对象表达式
51
+ TypeTable: { name: "TypeTable", mode: "visual", items: "TypeItem" },
52
+ Image: {
53
+ name: "Image",
54
+ mode: "visual",
55
+ selfClosing: true,
56
+ attrs: ["src", "alt", "align", "width", "caption"],
57
+ boolAttrs: ["zoom"],
58
+ defaultAttrs: { align: "center" }
59
+ }
60
+ };
61
+ function getComponent(name) {
62
+ return COMPONENTS[name];
63
+ }
64
+ function getItemSpec(name) {
65
+ return ITEMS[name];
66
+ }
67
+ function listComponents() {
68
+ return Object.keys(COMPONENTS);
69
+ }
70
+ function isContainerWithItems(name) {
71
+ return Boolean(COMPONENTS[name]?.items);
72
+ }
73
+ var LT = 60;
74
+ var GT = 62;
75
+ var SLASH = 47;
76
+ var DQUOTE = 34;
77
+ var SQUOTE = 39;
78
+ var SPACE = 32;
79
+ function isKnownName(name) {
80
+ return Boolean(COMPONENTS[name]) || Boolean(ITEMS[name]);
81
+ }
82
+ function isSelfCloseAllowed(name) {
83
+ return COMPONENTS[name]?.selfClosing === true || ITEMS[name]?.selfClosing === true;
84
+ }
85
+ var OPEN_STATE = /* @__PURE__ */ new WeakMap();
86
+ function stateOf(context) {
87
+ let state = OPEN_STATE.get(context.parser);
88
+ if (!state) {
89
+ state = { seq: 0, stack: [] };
90
+ OPEN_STATE.set(context.parser, state);
91
+ }
92
+ return state;
93
+ }
94
+ var jsxBlock = {
95
+ tokenize: tokenizeJsxBlock,
96
+ concrete: true
97
+ };
98
+ function jsxBlocks() {
99
+ return {
100
+ flow: {
101
+ [LT]: jsxBlock
102
+ }
103
+ };
104
+ }
105
+ function tokenizeJsxBlock(effects, ok, nok) {
106
+ const self = this;
107
+ let name = "";
108
+ let closingName = "";
109
+ let prevCode = null;
110
+ let quote = null;
111
+ let hasAttributes = false;
112
+ let previous;
113
+ const state = stateOf(self);
114
+ let myId = -1;
115
+ function popSelf() {
116
+ if (state.stack[state.stack.length - 1] === myId) state.stack.pop();
117
+ }
118
+ const nonLazyLine = { tokenize: tokenizeNonLazyLine, partial: true };
119
+ let nestedDepth = 0;
120
+ const closeConstruct = { tokenize: tokenizeCloseTag, partial: true };
121
+ const openConstruct = { tokenize: tokenizeOpenProbe, partial: true };
122
+ return start;
123
+ function start(code) {
124
+ if (code !== LT) return nok(code);
125
+ effects.enter("jsxBlock");
126
+ effects.enter("jsxBlockOpenTag");
127
+ effects.enter("jsxBlockOpenTagMarker");
128
+ effects.consume(code);
129
+ effects.exit("jsxBlockOpenTagMarker");
130
+ return openName;
131
+ }
132
+ function openName(code) {
133
+ if (code !== null && asciiAlpha(code)) {
134
+ effects.enter("jsxBlockName");
135
+ effects.consume(code);
136
+ return inName;
137
+ }
138
+ return nok(code);
139
+ }
140
+ function inName(code) {
141
+ if (code !== null && asciiAlphanumeric(code)) {
142
+ effects.consume(code);
143
+ return inName;
144
+ }
145
+ name = self.sliceSerialize(effects.exit("jsxBlockName"), true);
146
+ if (!isKnownName(name)) return nok(code);
147
+ return afterName(code);
148
+ }
149
+ function afterName(code) {
150
+ if (code === GT) return closeOpenTag(code, false);
151
+ if (code === null || markdownLineEnding(code)) return nok(code);
152
+ hasAttributes = true;
153
+ effects.enter("jsxBlockAttributes");
154
+ return attributes(code);
155
+ }
156
+ function attributes(code) {
157
+ if (code === null || markdownLineEnding(code)) return nok(code);
158
+ if (quote !== null) {
159
+ effects.consume(code);
160
+ if (code === quote) quote = null;
161
+ prevCode = code;
162
+ return attributes;
163
+ }
164
+ if (code === DQUOTE || code === SQUOTE) {
165
+ quote = code;
166
+ effects.consume(code);
167
+ prevCode = code;
168
+ return attributes;
169
+ }
170
+ if (code === GT) return closeOpenTag(code, prevCode === SLASH);
171
+ effects.consume(code);
172
+ prevCode = code;
173
+ return attributes;
174
+ }
175
+ function closeOpenTag(code, selfClosing) {
176
+ if (selfClosing && !isSelfCloseAllowed(name)) return nok(code);
177
+ effects.enter("jsxBlockOpenTagEnd");
178
+ effects.consume(code);
179
+ effects.exit("jsxBlockOpenTagEnd");
180
+ if (hasAttributes) effects.exit("jsxBlockAttributes");
181
+ effects.exit("jsxBlockOpenTag");
182
+ if (!selfClosing) {
183
+ myId = state.seq + 1;
184
+ state.seq = myId;
185
+ state.stack.push(myId);
186
+ }
187
+ return selfClosing ? finishBlock : openAfter;
188
+ }
189
+ function openAfter(code) {
190
+ if (code === null) return unclosed(code);
191
+ if (markdownLineEnding(code)) {
192
+ if (self.interrupt) {
193
+ popSelf();
194
+ effects.exit("jsxBlock");
195
+ return ok(code);
196
+ }
197
+ return effects.attempt(nonLazyLine, contentStart, unclosed)(code);
198
+ }
199
+ popSelf();
200
+ return nok(code);
201
+ }
202
+ function contentStart(code) {
203
+ effects.enter("jsxBlockContent");
204
+ return lineStart(code);
205
+ }
206
+ function lineStart(code) {
207
+ return effects.check(closeConstruct, closeDetected, notClose)(code);
208
+ }
209
+ function closeDetected(code) {
210
+ if (nestedDepth > 0) {
211
+ nestedDepth -= 1;
212
+ return chunkStart(code);
213
+ }
214
+ return effects.attempt(closeConstruct, afterContent, chunkStart)(code);
215
+ }
216
+ function notClose(code) {
217
+ return effects.check(openConstruct, openDetected, chunkStart)(code);
218
+ }
219
+ function openDetected(code) {
220
+ nestedDepth += 1;
221
+ return chunkStart(code);
222
+ }
223
+ function chunkStart(code) {
224
+ if (code === null) return afterContent(code);
225
+ return chunkNonLazyStart(code);
226
+ }
227
+ function chunkNonLazyStart(code) {
228
+ const token = effects.enter("chunkDocument", { contentType: "document", previous });
229
+ if (previous) previous.next = token;
230
+ previous = token;
231
+ return contentContinue(code);
232
+ }
233
+ function contentContinue(code) {
234
+ if (code === null) {
235
+ const t = effects.exit("chunkDocument");
236
+ self.parser.lazy[t.start.line] = false;
237
+ return afterContent(code);
238
+ }
239
+ if (markdownLineEnding(code)) {
240
+ return nonLazyLineAfter(code);
241
+ }
242
+ effects.consume(code);
243
+ return contentContinue;
244
+ }
245
+ function nonLazyLineAfter(code) {
246
+ effects.consume(code);
247
+ const t = effects.exit("chunkDocument");
248
+ self.parser.lazy[t.start.line] = false;
249
+ return lineStart;
250
+ }
251
+ function afterContent(code) {
252
+ effects.exit("jsxBlockContent");
253
+ return finishBlock(code);
254
+ }
255
+ function finishBlock(code) {
256
+ popSelf();
257
+ effects.exit("jsxBlock");
258
+ return ok(code);
259
+ }
260
+ function unclosed(code) {
261
+ popSelf();
262
+ effects.exit("jsxBlock");
263
+ return ok(code);
264
+ }
265
+ function tokenizeCloseTag(effects2, ok2, nok2) {
266
+ return closeStart;
267
+ function closeStart(code) {
268
+ if (code !== LT) return nok2(code);
269
+ effects2.enter("jsxBlockCloseTag");
270
+ effects2.enter("jsxBlockCloseTagMarker");
271
+ effects2.consume(code);
272
+ return closeSlash;
273
+ }
274
+ function closeSlash(code) {
275
+ if (code !== SLASH) return nok2(code);
276
+ effects2.consume(code);
277
+ effects2.exit("jsxBlockCloseTagMarker");
278
+ return closeNameStart;
279
+ }
280
+ function closeNameStart(code) {
281
+ if (code !== null && asciiAlpha(code)) {
282
+ effects2.enter("jsxBlockCloseName");
283
+ effects2.consume(code);
284
+ return closeNameRest;
285
+ }
286
+ return nok2(code);
287
+ }
288
+ function closeNameRest(code) {
289
+ if (code !== null && asciiAlphanumeric(code)) {
290
+ effects2.consume(code);
291
+ return closeNameRest;
292
+ }
293
+ closingName = self.sliceSerialize(effects2.exit("jsxBlockCloseName"), true);
294
+ if (closingName !== name) return nok2(code);
295
+ if (state.stack[state.stack.length - 1] !== myId) return nok2(code);
296
+ if (code !== GT) return nok2(code);
297
+ effects2.enter("jsxBlockCloseTagEnd");
298
+ effects2.consume(code);
299
+ effects2.exit("jsxBlockCloseTagEnd");
300
+ effects2.exit("jsxBlockCloseTag");
301
+ return ok2(code);
302
+ }
303
+ }
304
+ function tokenizeOpenProbe(effects2, ok2, nok2) {
305
+ let index = 0;
306
+ let probeQuote = null;
307
+ let probePrev = null;
308
+ return probeStart;
309
+ function probeStart(code) {
310
+ if (code !== LT) return nok2(code);
311
+ effects2.enter("jsxBlockProbe");
312
+ effects2.consume(code);
313
+ return probeName;
314
+ }
315
+ function probeName(code) {
316
+ if (index < name.length) {
317
+ if (code !== name.charCodeAt(index)) return nok2(code);
318
+ effects2.consume(code);
319
+ index += 1;
320
+ return probeName;
321
+ }
322
+ if (code === SPACE) {
323
+ effects2.consume(code);
324
+ return probeAttrs;
325
+ }
326
+ if (code === GT) {
327
+ effects2.consume(code);
328
+ effects2.exit("jsxBlockProbe");
329
+ return ok2(code);
330
+ }
331
+ return nok2(code);
332
+ }
333
+ function probeAttrs(code) {
334
+ if (code === null || markdownLineEnding(code)) return nok2(code);
335
+ if (probeQuote !== null) {
336
+ effects2.consume(code);
337
+ if (code === probeQuote) probeQuote = null;
338
+ return probeAttrs;
339
+ }
340
+ if (code === DQUOTE || code === SQUOTE) {
341
+ probeQuote = code;
342
+ effects2.consume(code);
343
+ return probeAttrs;
344
+ }
345
+ if (code === GT) {
346
+ effects2.consume(code);
347
+ effects2.exit("jsxBlockProbe");
348
+ return probePrev === SLASH ? nok2(code) : ok2(code);
349
+ }
350
+ probePrev = code;
351
+ effects2.consume(code);
352
+ return probeAttrs;
353
+ }
354
+ }
355
+ function tokenizeNonLazyLine(effects2, ok2, nok2) {
356
+ return nonLazyStart;
357
+ function nonLazyStart(code) {
358
+ effects2.enter("lineEnding");
359
+ effects2.consume(code);
360
+ effects2.exit("lineEnding");
361
+ return nonLazyAfter;
362
+ }
363
+ function nonLazyAfter(code) {
364
+ return self.parser.lazy[self.now().line] ? nok2(code) : ok2(code);
365
+ }
366
+ }
367
+ }
368
+
369
+ // src/syntax/jsx-mdast.ts
370
+ var OPEN_TAG_RE = /^<([A-Za-z][\w]*)([\s\S]*?)(\/?)>$/;
371
+ var ATTR_RE = /([A-Za-z_][\w-]*)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/g;
372
+ function parseOpenTag(raw) {
373
+ const match = OPEN_TAG_RE.exec(raw.trim());
374
+ if (!match) return { name: "", attributes: {}, selfClosing: false };
375
+ const attributes = {};
376
+ const rest = match[2] ?? "";
377
+ ATTR_RE.lastIndex = 0;
378
+ let item;
379
+ while ((item = ATTR_RE.exec(rest)) !== null) {
380
+ const key = item[1];
381
+ if (!key) continue;
382
+ const value = item[2] ?? item[3];
383
+ attributes[key] = value === void 0 ? true : value;
384
+ }
385
+ return { name: match[1], attributes, selfClosing: match[3] === "/" };
386
+ }
387
+ function jsxFromMarkdown() {
388
+ return {
389
+ enter: {
390
+ jsxBlock: enterBlock
391
+ },
392
+ exit: {
393
+ jsxBlockOpenTag: exitOpenTag,
394
+ jsxBlock: exitBlock
395
+ }
396
+ };
397
+ }
398
+ function jsxToMarkdown() {
399
+ return {
400
+ handlers: {
401
+ jsxBlock: handleJsxBlock
402
+ }
403
+ };
404
+ }
405
+ function enterBlock(token) {
406
+ const node = {
407
+ type: "jsxBlock",
408
+ name: "",
409
+ attributes: {},
410
+ selfClosing: false,
411
+ children: []
412
+ };
413
+ this.enter(node, token);
414
+ }
415
+ function exitOpenTag(token) {
416
+ const node = this.stack[this.stack.length - 1];
417
+ const parsed = parseOpenTag(this.sliceSerialize(token));
418
+ node.name = parsed.name;
419
+ node.attributes = parsed.attributes;
420
+ node.selfClosing = parsed.selfClosing;
421
+ node.data = { closed: true };
422
+ }
423
+ function exitBlock(token) {
424
+ this.exit(token);
425
+ }
426
+ function serializeAttributes(attributes) {
427
+ return Object.entries(attributes).map(([key, value]) => {
428
+ if (value === true) return ` ${key}`;
429
+ return ` ${key}="${String(value).replace(/"/g, "&quot;")}"`;
430
+ }).join("");
431
+ }
432
+ function handleJsxBlock(node, _parent, state, info) {
433
+ const attrs = serializeAttributes(node.attributes ?? {});
434
+ if (node.selfClosing) return `<${node.name}${attrs} />`;
435
+ const inner = state.containerFlow(node, info);
436
+ if (node.data?.closed === false) return `<${node.name}${attrs}>
437
+
438
+ ${inner}`;
439
+ return `<${node.name}${attrs}>
440
+
441
+ ${inner}
442
+
443
+ </${node.name}>`;
444
+ }
445
+
446
+ // src/syntax/jsx-remark.ts
447
+ function remarkJsxBlocks() {
448
+ const data = this.data();
449
+ (data.micromarkExtensions ??= []).push(jsxBlocks());
450
+ (data.fromMarkdownExtensions ??= []).push(jsxFromMarkdown());
451
+ (data.toMarkdownExtensions ??= []).push(jsxToMarkdown());
452
+ return void 0;
453
+ }
454
+
455
+ // src/blocks.ts
456
+ function isJsxBlock(node) {
457
+ return node.type === "jsxBlock";
458
+ }
459
+ function rangeOf(node) {
460
+ const start = node.position?.start.offset ?? 0;
461
+ const end = node.position?.end.offset ?? start;
462
+ return [start, end];
463
+ }
464
+ function toBlocks(children, source, depth) {
465
+ return children.map((child) => toBlock(child, source, depth));
466
+ }
467
+ function toBlock(node, source, depth) {
468
+ const [start, end] = rangeOf(node);
469
+ if (isJsxBlock(node)) {
470
+ const spec = COMPONENTS[node.name];
471
+ const children = node.children ?? [];
472
+ const itemNames = spec?.items ? Array.isArray(spec.items) ? spec.items : [spec.items] : [];
473
+ if (itemNames.length > 0) {
474
+ const items = children.filter(isJsxBlock).filter((child) => itemNames.includes(child.name)).map((child) => {
475
+ const [itemStart, itemEnd] = rangeOf(child);
476
+ return {
477
+ name: child.name,
478
+ attrs: child.attributes,
479
+ // 子项内部再出现的容器属于下一层(与 policy 的计数口径一致)
480
+ blocks: toBlocks(child.children ?? [], source, depth + 1),
481
+ start: itemStart,
482
+ end: itemEnd
483
+ };
484
+ });
485
+ return {
486
+ kind: "container",
487
+ name: node.name,
488
+ attrs: node.attributes,
489
+ depth,
490
+ blocks: [],
491
+ items,
492
+ start,
493
+ end
494
+ };
495
+ }
496
+ return {
497
+ kind: "container",
498
+ name: node.name,
499
+ attrs: node.attributes,
500
+ depth,
501
+ blocks: toBlocks(children, source, depth + 1),
502
+ items: [],
503
+ start,
504
+ end
505
+ };
506
+ }
507
+ if (node.type === "html") {
508
+ return { kind: "source", text: source.slice(start, end), reason: "html", start, end };
509
+ }
510
+ if (node.type === "definition") {
511
+ return { kind: "source", text: source.slice(start, end), reason: "definition", start, end };
512
+ }
513
+ return { kind: "visual", type: node.type, start, end };
514
+ }
515
+ function extractBlocks(tree, source) {
516
+ return toBlocks(tree.children, source, 1);
517
+ }
518
+
519
+ // src/policy.ts
520
+ function isJsxBlock2(node) {
521
+ return node.type === "jsxBlock";
522
+ }
523
+ function sliceNode(source, node) {
524
+ const start = node.position?.start.offset;
525
+ const end = node.position?.end.offset;
526
+ if (typeof start !== "number" || typeof end !== "number") return "";
527
+ return source.slice(start, end);
528
+ }
529
+ function walk(parent, source, depth, maxDepth, out) {
530
+ const children = parent.children;
531
+ if (!children) return;
532
+ const next = [];
533
+ for (const child of children) {
534
+ if (!isJsxBlock2(child)) {
535
+ walk(child, source, depth, maxDepth, out);
536
+ next.push(child);
537
+ continue;
538
+ }
539
+ const isContainer = Boolean(COMPONENTS[child.name]);
540
+ const childDepth = depth + (isContainer ? 1 : 0);
541
+ if (isContainer && childDepth > maxDepth) {
542
+ const text = sliceNode(source, child);
543
+ const line = child.position?.start.line ?? 1;
544
+ out.push({
545
+ code: "DEPTH_EXCEEDED",
546
+ level: "warn",
547
+ line,
548
+ message: `\u7B2C ${childDepth} \u5C42\u5BB9\u5668 ${child.name} \u8D85\u51FA\u4E0A\u9650 ${maxDepth}\uFF0C\u5DF2\u6309\u6E90\u7801\u663E\u793A`,
549
+ range: [child.position?.start.offset ?? 0, child.position?.end.offset ?? 0]
550
+ });
551
+ const fallback = { type: "text", value: text };
552
+ next.push(fallback);
553
+ continue;
554
+ }
555
+ walk(child, source, childDepth, maxDepth, out);
556
+ next.push(child);
557
+ }
558
+ parent.children = next;
559
+ }
560
+ function enforceMaxDepth(tree, source, maxDepth = MAX_CONTAINER_DEPTH) {
561
+ const diagnostics = [];
562
+ walk(tree, source, 0, maxDepth, diagnostics);
563
+ return diagnostics;
564
+ }
565
+ function hasCloseTag(block, source) {
566
+ const start = block.position?.start.offset ?? 0;
567
+ const end = block.position?.end.offset ?? 0;
568
+ if (end <= start) return false;
569
+ const body = new RegExp(`</${block.name}\\s*>`);
570
+ if (body.test(source.slice(start, end))) return true;
571
+ return new RegExp(`^\\s*</${block.name}\\s*>`).test(source.slice(end, end + 64));
572
+ }
573
+ function collectUnclosed(tree, source) {
574
+ const diagnostics = [];
575
+ const visit5 = (node) => {
576
+ if (node.type === "jsxBlock") {
577
+ const block = node;
578
+ if (!block.selfClosing && !hasCloseTag(block, source)) {
579
+ block.data = { ...block.data ?? {}, closed: false };
580
+ diagnostics.push({
581
+ code: "UNCLOSED_TAG",
582
+ level: "warn",
583
+ line: block.position?.start.line ?? 1,
584
+ message: `<${block.name}> \u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5EF6\u4F38\u5230\u6587\u672B\u5904\u7406`,
585
+ range: [block.position?.start.offset ?? 0, block.position?.end.offset ?? 0]
586
+ });
587
+ }
588
+ }
589
+ const children = node.children;
590
+ if (children) for (const child of children) visit5(child);
591
+ };
592
+ visit5(tree);
593
+ return diagnostics;
594
+ }
595
+
596
+ // src/policy-tags.ts
597
+ var URL_ATTRS = ["href", "src"];
598
+ var HTML_OPEN_TAG = /^<([A-Z][A-Za-z0-9]*)/;
599
+ var KNOWN_NAMES = /* @__PURE__ */ new Set([...Object.keys(COMPONENTS), ...Object.keys(ITEMS)]);
600
+ function forEachNode(node, fn) {
601
+ if (node.type !== "root") fn(node);
602
+ const children = node.children;
603
+ if (!children) return;
604
+ for (const child of children) forEachNode(child, fn);
605
+ }
606
+ function collectUnsafeUrls(tree) {
607
+ const diagnostics = [];
608
+ const report = (line, label, url) => {
609
+ diagnostics.push({
610
+ code: "UNSAFE_HREF",
611
+ level: "warn",
612
+ line,
613
+ message: `${label} \u7684\u534F\u8BAE\u4E0D\u53D7\u652F\u6301\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u4E0D\u53EF\u70B9\u51FB\uFF1A${url}`
614
+ });
615
+ };
616
+ forEachNode(tree, (node) => {
617
+ const line = node.position?.start.line ?? 1;
618
+ if (node.type === "jsxBlock") {
619
+ const block = node;
620
+ for (const key of URL_ATTRS) {
621
+ const value = block.attributes?.[key];
622
+ if (typeof value === "string" && value.length > 0 && !isSafeHref(value)) {
623
+ report(line, `<${block.name} ${key}>`, value);
624
+ }
625
+ }
626
+ return;
627
+ }
628
+ if (node.type === "link" || node.type === "image") {
629
+ const url = node.url;
630
+ if (!isSafeHref(url)) report(line, node.type === "link" ? "\u94FE\u63A5" : "\u56FE\u7247", url);
631
+ }
632
+ });
633
+ return diagnostics;
634
+ }
635
+ function collectUnknownTags(tree) {
636
+ const diagnostics = [];
637
+ forEachNode(tree, (node) => {
638
+ if (node.type !== "html") return;
639
+ const match = HTML_OPEN_TAG.exec(String(node.value ?? "").trim());
640
+ if (!match) return;
641
+ const name = match[1];
642
+ if (KNOWN_NAMES.has(name)) return;
643
+ diagnostics.push({
644
+ code: "UNKNOWN_TAG",
645
+ level: "warn",
646
+ line: node.position?.start.line ?? 1,
647
+ message: `<${name}> \u4E0D\u662F\u5DF2\u6CE8\u518C\u7684\u7EC4\u4EF6\uFF0C\u5DF2\u6309\u6587\u672C\u663E\u793A`
648
+ });
649
+ });
650
+ return diagnostics;
651
+ }
652
+
653
+ // src/parse.ts
654
+ function parse(md, options) {
655
+ const source = md ?? "";
656
+ const tree = fromMarkdown(source, {
657
+ // GFM(表格 / 删除线 / 任务列表)、数学公式与尖括号块并列注册,解析与序列化保持同一口径。
658
+ // math 必须在此注册:否则 `$…$` 会退化成普通文本,序列化时把 `_`、`\` 当文本转义,
659
+ // 保存一次公式即变形(渲染侧走 remark-math,故表现为"看着正常、存下来坏了")。
660
+ extensions: [gfm(), math(), jsxBlocks()],
661
+ mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown(), jsxFromMarkdown()]
662
+ });
663
+ const diagnostics = [
664
+ ...enforceMaxDepth(tree, source, options?.maxDepth),
665
+ ...collectUnclosed(tree, source),
666
+ ...collectUnsafeUrls(tree),
667
+ ...collectUnknownTags(tree)
668
+ ];
669
+ const blocks = extractBlocks(tree, source);
670
+ return { tree, blocks, diagnostics };
671
+ }
672
+
673
+ // src/format.ts
674
+ var TAG_LINE = /^(\s*)<(\/?)([A-Z][A-Za-z0-9]*)((?:\s[^>]*)?)(\/?)>\s*$/;
675
+ var FENCE_LINE = /^\s*(`{3,}|~{3,})/;
676
+ function normalizeMarkdown(md) {
677
+ const lines = (md ?? "").replace(/\r\n?/g, "\n").split("\n");
678
+ const out = [];
679
+ let fenceChar = null;
680
+ const pushBlank = () => {
681
+ if (out.length > 0 && out[out.length - 1].trim() !== "") out.push("");
682
+ };
683
+ for (let i = 0; i < lines.length; i += 1) {
684
+ const line = lines[i];
685
+ const fence = FENCE_LINE.exec(line);
686
+ if (fenceChar !== null) {
687
+ out.push(line);
688
+ if (fence && fence[1].startsWith(fenceChar)) fenceChar = null;
689
+ continue;
690
+ }
691
+ if (fence) {
692
+ fenceChar = fence[1][0];
693
+ out.push(line);
694
+ continue;
695
+ }
696
+ const tag = TAG_LINE.exec(line);
697
+ if (tag && tag[1] === "") {
698
+ pushBlank();
699
+ out.push(line.trim());
700
+ const next = lines[i + 1];
701
+ if (next !== void 0 && next.trim() !== "") out.push("");
702
+ continue;
703
+ }
704
+ if (line.trim() === "") {
705
+ if (out.length > 0 && out[out.length - 1].trim() === "") continue;
706
+ out.push("");
707
+ continue;
708
+ }
709
+ out.push(line);
710
+ }
711
+ while (out.length > 0 && out[out.length - 1] === "") out.pop();
712
+ return out.join("\n");
713
+ }
714
+ var URL_PROPS = ["href", "src"];
715
+ function rehypeSafeUrls() {
716
+ return (tree) => {
717
+ visit(tree, "element", (node) => {
718
+ for (const key of URL_PROPS) {
719
+ const value = node.properties[key];
720
+ if (typeof value !== "string" || value.length === 0) continue;
721
+ if (isSafeHref(value)) continue;
722
+ if (key === "href") node.properties[key] = "#";
723
+ else delete node.properties[key];
724
+ }
725
+ });
726
+ };
727
+ }
728
+ function rehypeSafeAnchors() {
729
+ return (tree) => {
730
+ visit(tree, "element", (node) => {
731
+ const href = node.properties?.href;
732
+ if (typeof href !== "string" || !href.startsWith("#")) return;
733
+ try {
734
+ node.properties.href = `#${decodeURIComponent(href.slice(1))}`;
735
+ } catch {
736
+ }
737
+ });
738
+ };
739
+ }
740
+ function textOf(node) {
741
+ let out = "";
742
+ for (const child of node.children ?? []) {
743
+ if (child.type === "text") out += child.value;
744
+ else if (child.type === "element") out += textOf(child);
745
+ }
746
+ return out;
747
+ }
748
+ function langOf(code) {
749
+ const classes = code.properties?.className;
750
+ const list = Array.isArray(classes) ? classes.map(String) : [];
751
+ const found = list.find((item) => item.startsWith("language-"));
752
+ return found ? found.slice("language-".length) : "text";
753
+ }
754
+ function titleOf(code) {
755
+ const meta = code.data?.meta;
756
+ if (typeof meta !== "string") return void 0;
757
+ const matched = /title=["']?([^"'\s]+)["']?/.exec(meta);
758
+ return matched ? matched[1] : void 0;
759
+ }
760
+ function isCodeElement(child) {
761
+ return child.type === "element" && child.tagName === "code";
762
+ }
763
+ function rehypeCodeMeta() {
764
+ return (tree) => {
765
+ visit(tree, "element", (node) => {
766
+ if (node.tagName !== "pre") return;
767
+ const code = (node.children ?? []).find(isCodeElement);
768
+ if (!code) return;
769
+ const title = titleOf(code);
770
+ node.properties = {
771
+ ...node.properties,
772
+ "data-code-raw": textOf(code),
773
+ "data-code-lang": langOf(code),
774
+ ...title ? { "data-code-title": title } : {}
775
+ };
776
+ });
777
+ return void 0;
778
+ };
779
+ }
780
+ var BLOCK_TAGS = /* @__PURE__ */ new Set([
781
+ "p",
782
+ "h1",
783
+ "h2",
784
+ "h3",
785
+ "h4",
786
+ "h5",
787
+ "h6",
788
+ "ul",
789
+ "ol",
790
+ "li",
791
+ "blockquote",
792
+ "pre",
793
+ "table",
794
+ "figure",
795
+ "hr"
796
+ ]);
797
+ function rehypeSourcePositions() {
798
+ return (tree) => {
799
+ visit(tree, "element", (node) => {
800
+ const tag = node.tagName.toLowerCase();
801
+ if (!BLOCK_TAGS.has(tag)) return;
802
+ const start = node.position?.start.offset;
803
+ if (typeof start !== "number") return;
804
+ node.properties = node.properties ?? {};
805
+ node.properties["data-src-start"] = String(start);
806
+ });
807
+ return void 0;
808
+ };
809
+ }
810
+ function jsxBlockToHast(state, node) {
811
+ const properties = {};
812
+ for (const [key, value] of Object.entries(node.attributes ?? {})) {
813
+ properties[key] = value;
814
+ }
815
+ return {
816
+ type: "element",
817
+ tagName: node.name,
818
+ properties,
819
+ children: state.all(node)
820
+ };
821
+ }
822
+ function createProcessor(extraRemark, extraRehype, sourcePositions) {
823
+ return unified().use(remarkParse).use(remarkJsxBlocks).use(remarkGfm).use(remarkMath).use(extraRemark ?? []).use(remarkRehype, { handlers: { jsxBlock: jsxBlockToHast } }).use(rehypeSafeUrls).use(rehypeSafeAnchors).use(sourcePositions ? [rehypeSourcePositions] : []).use(rehypeCodeMeta).use(rehypeSlug).use(extraRehype ?? []).use(rehypeKatex);
824
+ }
825
+ function MarkdownRenderer({
826
+ content,
827
+ className,
828
+ config
829
+ }) {
830
+ const overrides = config?.components;
831
+ const extraRemark = config?.remarkPlugins;
832
+ const extraRehype = config?.rehypePlugins;
833
+ const sourcePositions = config?.sourcePositions;
834
+ const processor = useMemo(
835
+ () => createProcessor(extraRemark, extraRehype, sourcePositions),
836
+ [extraRemark, extraRehype, sourcePositions]
837
+ );
838
+ const rendered = useMemo(() => {
839
+ const source = content ?? "";
840
+ const mdast = processor.parse(source);
841
+ enforceMaxDepth(mdast, source);
842
+ const hast = processor.runSync(mdast);
843
+ return toJsxRuntime(hast, {
844
+ Fragment,
845
+ jsx,
846
+ jsxs,
847
+ components: { ...mdxComponents, ...overrides }
848
+ });
849
+ }, [content, overrides, processor]);
850
+ return /* @__PURE__ */ jsx("div", { className, children: rendered });
851
+ }
852
+
853
+ export { COMPONENTS, ITEMS, MAX_CONTAINER_DEPTH, MarkdownRenderer, extractBlocks, getComponent, getItemSpec, isContainerWithItems, jsxBlocks, jsxFromMarkdown, jsxToMarkdown, listComponents, normalizeMarkdown, parse, parseOpenTag, remarkJsxBlocks };
854
+ //# sourceMappingURL=chunk-3GDOWIMO.js.map
855
+ //# sourceMappingURL=chunk-3GDOWIMO.js.map