@simon_he/vue-tui 1.1.12 → 1.1.14

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.
package/dist/agent.cjs CHANGED
@@ -1009,6 +1009,19 @@ function sliceByCellsRange(text2, startCells, endCells, provider = currentTextWi
1009
1009
  out.push(g), cells = next;
1010
1010
  }), out.length ? out.join("") : "";
1011
1011
  }
1012
+ function sliceByCellsRangeForSelection(text2, startCells, endCells, provider = currentTextWidthProvider()) {
1013
+ if (startCells = Math.max(0, Math.floor(startCells)), endCells = Math.max(0, Math.floor(endCells)), endCells <= startCells || !text2)
1014
+ return "";
1015
+ if (hasAsciiFastPath(provider) && isAscii(text2))
1016
+ return text2.slice(startCells, endCells);
1017
+ let out = [], cells = 0;
1018
+ return forEachGrapheme(text2, (g) => {
1019
+ let leadingCell = cells;
1020
+ if (cells += charCellWidth(g, provider), leadingCell >= endCells)
1021
+ return !1;
1022
+ leadingCell >= startCells && out.push(g);
1023
+ }), out.join("");
1024
+ }
1012
1025
  function padEndByCells(text2, width, provider = currentTextWidthProvider()) {
1013
1026
  width = Math.max(0, Math.floor(width));
1014
1027
  let cells = text2 && hasAsciiFastPath(provider) && isAscii(text2) ? text2.length : textCellWidth(text2, provider);
@@ -8900,7 +8913,7 @@ var virtualListInstanceSeq = 0, TVirtualList = (0, import_vue21.defineComponent)
8900
8913
  function textForSelectionRange(range) {
8901
8914
  let cols = Math.max(1, Math.floor(props.w));
8902
8915
  return terminalSelectionRowSpans(range, cols, itemCount.value).map((span) => {
8903
- let text2 = sliceByCellsRange(itemText(span.y), span.x0, span.x1);
8916
+ let text2 = sliceByCellsRangeForSelection(itemText(span.y), span.x0, span.x1);
8904
8917
  return span.x1 >= cols ? text2.trimEnd() : text2;
8905
8918
  }).join(`
8906
8919
  `);
@@ -9587,7 +9600,7 @@ var virtualRowsInstanceSeq = 0, EMPTY_RECT2 = Object.freeze({ x: 0, y: 0, w: 0,
9587
9600
  x1: span.x1,
9588
9601
  cols
9589
9602
  }) ?? ""
9590
- ) : sliceByCellsRange(itemText(span.y), span.x0, span.x1);
9603
+ ) : sliceByCellsRangeForSelection(itemText(span.y), span.x0, span.x1);
9591
9604
  return span.x1 >= cols ? text2.trimEnd() : text2;
9592
9605
  }).join(`
9593
9606
  `);
@@ -10325,7 +10338,7 @@ var TTranscriptView = (0, import_vue23.defineComponent)({
10325
10338
  let text2 = "";
10326
10339
  for (let segment of segments) {
10327
10340
  let start = Math.max(x0, segment.x0), end = Math.min(x1, segment.x1);
10328
- end <= start || !segment.selectable || (text2 += sliceByCellsRange(segment.text, start - segment.x0, end - segment.x0));
10341
+ end <= start || !segment.selectable || (text2 += sliceByCellsRangeForSelection(segment.text, start - segment.x0, end - segment.x0));
10329
10342
  }
10330
10343
  return text2;
10331
10344
  }
@@ -10354,7 +10367,7 @@ var TTranscriptView = (0, import_vue23.defineComponent)({
10354
10367
  }
10355
10368
  function selectionTextForVisualRowSpan(ctx) {
10356
10369
  let visualRow = ctx.item;
10357
- return visualRow ? visualRow.selectionSegments.length ? textForSelectionSegments(visualRow.selectionSegments, ctx.x0, ctx.x1) : sliceByCellsRange(selectionTextForVisualRow(visualRow), ctx.x0, ctx.x1) : "";
10370
+ return visualRow ? visualRow.selectionSegments.length ? textForSelectionSegments(visualRow.selectionSegments, ctx.x0, ctx.x1) : sliceByCellsRangeForSelection(selectionTextForVisualRow(visualRow), ctx.x0, ctx.x1) : "";
10358
10371
  }
10359
10372
  return () => (0, import_vue23.h)(TVirtualRows, {
10360
10373
  ref: rowsRef,
@@ -12613,7 +12626,7 @@ var TLogView = (0, import_vue24.defineComponent)({
12613
12626
  function textForSelectionRange(range) {
12614
12627
  let cols = currentWrapWidth(), rows = estimatedVisualRowCount();
12615
12628
  return terminalSelectionRowSpans(range, cols, rows).map((span) => {
12616
- let text2 = sliceByCellsRange(textForVisualRow(span.y), span.x0, span.x1);
12629
+ let text2 = sliceByCellsRangeForSelection(textForVisualRow(span.y), span.x0, span.x1);
12617
12630
  return span.x1 >= cols ? text2.trimEnd() : text2;
12618
12631
  }).join(`
12619
12632
  `);
@@ -15157,7 +15170,7 @@ function loadBuiltinMathRasterizer() {
15157
15170
  })()), builtinRasterizerLoad;
15158
15171
  }
15159
15172
 
15160
- // node_modules/.pnpm/stream-markdown-parser@1.2.12/node_modules/stream-markdown-parser/dist/index.js
15173
+ // node_modules/.pnpm/stream-markdown-parser@1.2.20/node_modules/stream-markdown-parser/dist/index.js
15161
15174
  var __create2 = Object.create, __defProp$1 = Object.defineProperty, __getOwnPropDesc2 = Object.getOwnPropertyDescriptor, __getOwnPropNames2 = Object.getOwnPropertyNames, __getProtoOf2 = Object.getPrototypeOf, __hasOwnProp2 = Object.prototype.hasOwnProperty, __commonJS = (cb, mod) => function() {
15162
15175
  return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15163
15176
  }, __export$1 = (all) => {
@@ -15540,7 +15553,756 @@ var require_markdown_it_task_checkbox = /* @__PURE__ */ __commonJS({ "../../node
15540
15553
  function startsWithTodoMarkdown(token) {
15541
15554
  return /^\[[xX \u00A0]\][ \u00A0]/.test(token.content);
15542
15555
  }
15543
- } }), decodeMap = /* @__PURE__ */ new Map([
15556
+ } }), import_markdown_it_task_checkbox = /* @__PURE__ */ __toESM2(require_markdown_it_task_checkbox(), 1), ambiguousMinimalCodePoint = 161, ambiguousMaximumCodePoint = 1114109, ambiguousRanges = [
15557
+ 161,
15558
+ 161,
15559
+ 164,
15560
+ 164,
15561
+ 167,
15562
+ 168,
15563
+ 170,
15564
+ 170,
15565
+ 173,
15566
+ 174,
15567
+ 176,
15568
+ 180,
15569
+ 182,
15570
+ 186,
15571
+ 188,
15572
+ 191,
15573
+ 198,
15574
+ 198,
15575
+ 208,
15576
+ 208,
15577
+ 215,
15578
+ 216,
15579
+ 222,
15580
+ 225,
15581
+ 230,
15582
+ 230,
15583
+ 232,
15584
+ 234,
15585
+ 236,
15586
+ 237,
15587
+ 240,
15588
+ 240,
15589
+ 242,
15590
+ 243,
15591
+ 247,
15592
+ 250,
15593
+ 252,
15594
+ 252,
15595
+ 254,
15596
+ 254,
15597
+ 257,
15598
+ 257,
15599
+ 273,
15600
+ 273,
15601
+ 275,
15602
+ 275,
15603
+ 283,
15604
+ 283,
15605
+ 294,
15606
+ 295,
15607
+ 299,
15608
+ 299,
15609
+ 305,
15610
+ 307,
15611
+ 312,
15612
+ 312,
15613
+ 319,
15614
+ 322,
15615
+ 324,
15616
+ 324,
15617
+ 328,
15618
+ 331,
15619
+ 333,
15620
+ 333,
15621
+ 338,
15622
+ 339,
15623
+ 358,
15624
+ 359,
15625
+ 363,
15626
+ 363,
15627
+ 462,
15628
+ 462,
15629
+ 464,
15630
+ 464,
15631
+ 466,
15632
+ 466,
15633
+ 468,
15634
+ 468,
15635
+ 470,
15636
+ 470,
15637
+ 472,
15638
+ 472,
15639
+ 474,
15640
+ 474,
15641
+ 476,
15642
+ 476,
15643
+ 593,
15644
+ 593,
15645
+ 609,
15646
+ 609,
15647
+ 708,
15648
+ 708,
15649
+ 711,
15650
+ 711,
15651
+ 713,
15652
+ 715,
15653
+ 717,
15654
+ 717,
15655
+ 720,
15656
+ 720,
15657
+ 728,
15658
+ 731,
15659
+ 733,
15660
+ 733,
15661
+ 735,
15662
+ 735,
15663
+ 768,
15664
+ 879,
15665
+ 913,
15666
+ 929,
15667
+ 931,
15668
+ 937,
15669
+ 945,
15670
+ 961,
15671
+ 963,
15672
+ 969,
15673
+ 1025,
15674
+ 1025,
15675
+ 1040,
15676
+ 1103,
15677
+ 1105,
15678
+ 1105,
15679
+ 8208,
15680
+ 8208,
15681
+ 8211,
15682
+ 8214,
15683
+ 8216,
15684
+ 8217,
15685
+ 8220,
15686
+ 8221,
15687
+ 8224,
15688
+ 8226,
15689
+ 8228,
15690
+ 8231,
15691
+ 8240,
15692
+ 8240,
15693
+ 8242,
15694
+ 8243,
15695
+ 8245,
15696
+ 8245,
15697
+ 8251,
15698
+ 8251,
15699
+ 8254,
15700
+ 8254,
15701
+ 8308,
15702
+ 8308,
15703
+ 8319,
15704
+ 8319,
15705
+ 8321,
15706
+ 8324,
15707
+ 8364,
15708
+ 8364,
15709
+ 8451,
15710
+ 8451,
15711
+ 8453,
15712
+ 8453,
15713
+ 8457,
15714
+ 8457,
15715
+ 8467,
15716
+ 8467,
15717
+ 8470,
15718
+ 8470,
15719
+ 8481,
15720
+ 8482,
15721
+ 8486,
15722
+ 8486,
15723
+ 8491,
15724
+ 8491,
15725
+ 8531,
15726
+ 8532,
15727
+ 8539,
15728
+ 8542,
15729
+ 8544,
15730
+ 8555,
15731
+ 8560,
15732
+ 8569,
15733
+ 8585,
15734
+ 8585,
15735
+ 8592,
15736
+ 8601,
15737
+ 8632,
15738
+ 8633,
15739
+ 8658,
15740
+ 8658,
15741
+ 8660,
15742
+ 8660,
15743
+ 8679,
15744
+ 8679,
15745
+ 8704,
15746
+ 8704,
15747
+ 8706,
15748
+ 8707,
15749
+ 8711,
15750
+ 8712,
15751
+ 8715,
15752
+ 8715,
15753
+ 8719,
15754
+ 8719,
15755
+ 8721,
15756
+ 8721,
15757
+ 8725,
15758
+ 8725,
15759
+ 8730,
15760
+ 8730,
15761
+ 8733,
15762
+ 8736,
15763
+ 8739,
15764
+ 8739,
15765
+ 8741,
15766
+ 8741,
15767
+ 8743,
15768
+ 8748,
15769
+ 8750,
15770
+ 8750,
15771
+ 8756,
15772
+ 8759,
15773
+ 8764,
15774
+ 8765,
15775
+ 8776,
15776
+ 8776,
15777
+ 8780,
15778
+ 8780,
15779
+ 8786,
15780
+ 8786,
15781
+ 8800,
15782
+ 8801,
15783
+ 8804,
15784
+ 8807,
15785
+ 8810,
15786
+ 8811,
15787
+ 8814,
15788
+ 8815,
15789
+ 8834,
15790
+ 8835,
15791
+ 8838,
15792
+ 8839,
15793
+ 8853,
15794
+ 8853,
15795
+ 8857,
15796
+ 8857,
15797
+ 8869,
15798
+ 8869,
15799
+ 8895,
15800
+ 8895,
15801
+ 8978,
15802
+ 8978,
15803
+ 9312,
15804
+ 9449,
15805
+ 9451,
15806
+ 9547,
15807
+ 9552,
15808
+ 9587,
15809
+ 9600,
15810
+ 9615,
15811
+ 9618,
15812
+ 9621,
15813
+ 9632,
15814
+ 9633,
15815
+ 9635,
15816
+ 9641,
15817
+ 9650,
15818
+ 9651,
15819
+ 9654,
15820
+ 9655,
15821
+ 9660,
15822
+ 9661,
15823
+ 9664,
15824
+ 9665,
15825
+ 9670,
15826
+ 9672,
15827
+ 9675,
15828
+ 9675,
15829
+ 9678,
15830
+ 9681,
15831
+ 9698,
15832
+ 9701,
15833
+ 9711,
15834
+ 9711,
15835
+ 9733,
15836
+ 9734,
15837
+ 9737,
15838
+ 9737,
15839
+ 9742,
15840
+ 9743,
15841
+ 9756,
15842
+ 9756,
15843
+ 9758,
15844
+ 9758,
15845
+ 9792,
15846
+ 9792,
15847
+ 9794,
15848
+ 9794,
15849
+ 9824,
15850
+ 9825,
15851
+ 9827,
15852
+ 9829,
15853
+ 9831,
15854
+ 9834,
15855
+ 9836,
15856
+ 9837,
15857
+ 9839,
15858
+ 9839,
15859
+ 9886,
15860
+ 9887,
15861
+ 9919,
15862
+ 9919,
15863
+ 9926,
15864
+ 9933,
15865
+ 9935,
15866
+ 9939,
15867
+ 9941,
15868
+ 9953,
15869
+ 9955,
15870
+ 9955,
15871
+ 9960,
15872
+ 9961,
15873
+ 9963,
15874
+ 9969,
15875
+ 9972,
15876
+ 9972,
15877
+ 9974,
15878
+ 9977,
15879
+ 9979,
15880
+ 9980,
15881
+ 9982,
15882
+ 9983,
15883
+ 10045,
15884
+ 10045,
15885
+ 10102,
15886
+ 10111,
15887
+ 11094,
15888
+ 11097,
15889
+ 12872,
15890
+ 12879,
15891
+ 57344,
15892
+ 63743,
15893
+ 65024,
15894
+ 65039,
15895
+ 65533,
15896
+ 65533,
15897
+ 127232,
15898
+ 127242,
15899
+ 127248,
15900
+ 127277,
15901
+ 127280,
15902
+ 127337,
15903
+ 127344,
15904
+ 127373,
15905
+ 127375,
15906
+ 127376,
15907
+ 127387,
15908
+ 127404,
15909
+ 917760,
15910
+ 917999,
15911
+ 983040,
15912
+ 1048573,
15913
+ 1048576,
15914
+ 1114109
15915
+ ], fullwidthMinimalCodePoint = 12288, fullwidthMaximumCodePoint = 65510, fullwidthRanges = [
15916
+ 12288,
15917
+ 12288,
15918
+ 65281,
15919
+ 65376,
15920
+ 65504,
15921
+ 65510
15922
+ ], halfwidthMinimalCodePoint = 8361, halfwidthMaximumCodePoint = 65518, halfwidthRanges = [
15923
+ 8361,
15924
+ 8361,
15925
+ 65377,
15926
+ 65470,
15927
+ 65474,
15928
+ 65479,
15929
+ 65482,
15930
+ 65487,
15931
+ 65490,
15932
+ 65495,
15933
+ 65498,
15934
+ 65500,
15935
+ 65512,
15936
+ 65518
15937
+ ], narrowMinimalCodePoint = 32, narrowMaximumCodePoint = 10630, narrowRanges = [
15938
+ 32,
15939
+ 126,
15940
+ 162,
15941
+ 163,
15942
+ 165,
15943
+ 166,
15944
+ 172,
15945
+ 172,
15946
+ 175,
15947
+ 175,
15948
+ 10214,
15949
+ 10221,
15950
+ 10629,
15951
+ 10630
15952
+ ], wideMinimalCodePoint = 4352, wideMaximumCodePoint = 262141, wideRanges = [
15953
+ 4352,
15954
+ 4447,
15955
+ 8986,
15956
+ 8987,
15957
+ 9001,
15958
+ 9002,
15959
+ 9193,
15960
+ 9196,
15961
+ 9200,
15962
+ 9200,
15963
+ 9203,
15964
+ 9203,
15965
+ 9725,
15966
+ 9726,
15967
+ 9748,
15968
+ 9749,
15969
+ 9776,
15970
+ 9783,
15971
+ 9800,
15972
+ 9811,
15973
+ 9855,
15974
+ 9855,
15975
+ 9866,
15976
+ 9871,
15977
+ 9875,
15978
+ 9875,
15979
+ 9889,
15980
+ 9889,
15981
+ 9898,
15982
+ 9899,
15983
+ 9917,
15984
+ 9918,
15985
+ 9924,
15986
+ 9925,
15987
+ 9934,
15988
+ 9934,
15989
+ 9940,
15990
+ 9940,
15991
+ 9962,
15992
+ 9962,
15993
+ 9970,
15994
+ 9971,
15995
+ 9973,
15996
+ 9973,
15997
+ 9978,
15998
+ 9978,
15999
+ 9981,
16000
+ 9981,
16001
+ 9989,
16002
+ 9989,
16003
+ 9994,
16004
+ 9995,
16005
+ 10024,
16006
+ 10024,
16007
+ 10060,
16008
+ 10060,
16009
+ 10062,
16010
+ 10062,
16011
+ 10067,
16012
+ 10069,
16013
+ 10071,
16014
+ 10071,
16015
+ 10133,
16016
+ 10135,
16017
+ 10160,
16018
+ 10160,
16019
+ 10175,
16020
+ 10175,
16021
+ 11035,
16022
+ 11036,
16023
+ 11088,
16024
+ 11088,
16025
+ 11093,
16026
+ 11093,
16027
+ 11904,
16028
+ 11929,
16029
+ 11931,
16030
+ 12019,
16031
+ 12032,
16032
+ 12245,
16033
+ 12272,
16034
+ 12287,
16035
+ 12289,
16036
+ 12350,
16037
+ 12353,
16038
+ 12438,
16039
+ 12441,
16040
+ 12543,
16041
+ 12549,
16042
+ 12591,
16043
+ 12593,
16044
+ 12686,
16045
+ 12688,
16046
+ 12773,
16047
+ 12783,
16048
+ 12830,
16049
+ 12832,
16050
+ 12871,
16051
+ 12880,
16052
+ 42124,
16053
+ 42128,
16054
+ 42182,
16055
+ 43360,
16056
+ 43388,
16057
+ 44032,
16058
+ 55203,
16059
+ 63744,
16060
+ 64255,
16061
+ 65040,
16062
+ 65049,
16063
+ 65072,
16064
+ 65106,
16065
+ 65108,
16066
+ 65126,
16067
+ 65128,
16068
+ 65131,
16069
+ 94176,
16070
+ 94180,
16071
+ 94192,
16072
+ 94198,
16073
+ 94208,
16074
+ 101589,
16075
+ 101631,
16076
+ 101662,
16077
+ 101760,
16078
+ 101874,
16079
+ 110576,
16080
+ 110579,
16081
+ 110581,
16082
+ 110587,
16083
+ 110589,
16084
+ 110590,
16085
+ 110592,
16086
+ 110882,
16087
+ 110898,
16088
+ 110898,
16089
+ 110928,
16090
+ 110930,
16091
+ 110933,
16092
+ 110933,
16093
+ 110948,
16094
+ 110951,
16095
+ 110960,
16096
+ 111355,
16097
+ 119552,
16098
+ 119638,
16099
+ 119648,
16100
+ 119670,
16101
+ 126980,
16102
+ 126980,
16103
+ 127183,
16104
+ 127183,
16105
+ 127374,
16106
+ 127374,
16107
+ 127377,
16108
+ 127386,
16109
+ 127488,
16110
+ 127490,
16111
+ 127504,
16112
+ 127547,
16113
+ 127552,
16114
+ 127560,
16115
+ 127568,
16116
+ 127569,
16117
+ 127584,
16118
+ 127589,
16119
+ 127744,
16120
+ 127776,
16121
+ 127789,
16122
+ 127797,
16123
+ 127799,
16124
+ 127868,
16125
+ 127870,
16126
+ 127891,
16127
+ 127904,
16128
+ 127946,
16129
+ 127951,
16130
+ 127955,
16131
+ 127968,
16132
+ 127984,
16133
+ 127988,
16134
+ 127988,
16135
+ 127992,
16136
+ 128062,
16137
+ 128064,
16138
+ 128064,
16139
+ 128066,
16140
+ 128252,
16141
+ 128255,
16142
+ 128317,
16143
+ 128331,
16144
+ 128334,
16145
+ 128336,
16146
+ 128359,
16147
+ 128378,
16148
+ 128378,
16149
+ 128405,
16150
+ 128406,
16151
+ 128420,
16152
+ 128420,
16153
+ 128507,
16154
+ 128591,
16155
+ 128640,
16156
+ 128709,
16157
+ 128716,
16158
+ 128716,
16159
+ 128720,
16160
+ 128722,
16161
+ 128725,
16162
+ 128728,
16163
+ 128732,
16164
+ 128735,
16165
+ 128747,
16166
+ 128748,
16167
+ 128756,
16168
+ 128764,
16169
+ 128992,
16170
+ 129003,
16171
+ 129008,
16172
+ 129008,
16173
+ 129292,
16174
+ 129338,
16175
+ 129340,
16176
+ 129349,
16177
+ 129351,
16178
+ 129535,
16179
+ 129648,
16180
+ 129660,
16181
+ 129664,
16182
+ 129674,
16183
+ 129678,
16184
+ 129734,
16185
+ 129736,
16186
+ 129736,
16187
+ 129741,
16188
+ 129756,
16189
+ 129759,
16190
+ 129770,
16191
+ 129775,
16192
+ 129784,
16193
+ 131072,
16194
+ 196605,
16195
+ 196608,
16196
+ 262141
16197
+ ], isInRange = (ranges, codePoint) => {
16198
+ let low = 0, high = Math.floor(ranges.length / 2) - 1;
16199
+ for (; low <= high; ) {
16200
+ let mid = Math.floor((low + high) / 2), i = mid * 2;
16201
+ if (codePoint < ranges[i])
16202
+ high = mid - 1;
16203
+ else if (codePoint > ranges[i + 1])
16204
+ low = mid + 1;
16205
+ else
16206
+ return !0;
16207
+ }
16208
+ return !1;
16209
+ }, commonCjkCodePoint = 19968, [wideFastPathStart, wideFastPathEnd] = /* @__PURE__ */ findWideFastPathRange(wideRanges);
16210
+ function findWideFastPathRange(ranges) {
16211
+ let fastPathStart = ranges[0], fastPathEnd = ranges[1];
16212
+ for (let index = 0; index < ranges.length; index += 2) {
16213
+ let start = ranges[index], end = ranges[index + 1];
16214
+ if (commonCjkCodePoint >= start && commonCjkCodePoint <= end)
16215
+ return [start, end];
16216
+ end - start > fastPathEnd - fastPathStart && (fastPathStart = start, fastPathEnd = end);
16217
+ }
16218
+ return [fastPathStart, fastPathEnd];
16219
+ }
16220
+ var isAmbiguous = (codePoint) => codePoint < ambiguousMinimalCodePoint || codePoint > ambiguousMaximumCodePoint ? !1 : isInRange(ambiguousRanges, codePoint), isFullWidth = (codePoint) => codePoint < fullwidthMinimalCodePoint || codePoint > fullwidthMaximumCodePoint ? !1 : isInRange(fullwidthRanges, codePoint), isHalfWidth = (codePoint) => codePoint < halfwidthMinimalCodePoint || codePoint > halfwidthMaximumCodePoint ? !1 : isInRange(halfwidthRanges, codePoint), isNarrow = (codePoint) => codePoint < narrowMinimalCodePoint || codePoint > narrowMaximumCodePoint ? !1 : isInRange(narrowRanges, codePoint), isWide = (codePoint) => codePoint >= wideFastPathStart && codePoint <= wideFastPathEnd ? !0 : codePoint < wideMinimalCodePoint || codePoint > wideMaximumCodePoint ? !1 : isInRange(wideRanges, codePoint);
16221
+ function getCategory(codePoint) {
16222
+ return isAmbiguous(codePoint) ? "ambiguous" : isFullWidth(codePoint) ? "fullwidth" : isHalfWidth(codePoint) ? "halfwidth" : isNarrow(codePoint) ? "narrow" : isWide(codePoint) ? "wide" : "neutral";
16223
+ }
16224
+ function validate(codePoint) {
16225
+ if (!Number.isSafeInteger(codePoint))
16226
+ throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`);
16227
+ }
16228
+ function eastAsianWidthType(codePoint) {
16229
+ return validate(codePoint), getCategory(codePoint);
16230
+ }
16231
+ function isEmoji(uc) {
16232
+ return /^\p{Emoji_Presentation}/u.test(String.fromCodePoint(uc));
16233
+ }
16234
+ function isCjkBase(uc) {
16235
+ if (uc < 4352)
16236
+ return !1;
16237
+ switch (eastAsianWidthType(uc)) {
16238
+ case "fullwidth":
16239
+ case "halfwidth":
16240
+ return !0;
16241
+ case "wide":
16242
+ return !isEmoji(uc);
16243
+ case "narrow":
16244
+ return !1;
16245
+ case "ambiguous":
16246
+ return null;
16247
+ case "neutral":
16248
+ return /^\p{sc=Hangul}/u.test(String.fromCodePoint(uc));
16249
+ }
16250
+ }
16251
+ function is2PreviousCjk(uc, prev) {
16252
+ return isCjkBase(uc) ?? (prev === 65025 && isQuotationMark(uc));
16253
+ function isQuotationMark(uc$1) {
16254
+ return uc$1 === 8216 || uc$1 === 8217 || uc$1 === 8220 || uc$1 === 8221;
16255
+ }
16256
+ }
16257
+ function isPreviousCjk(uc) {
16258
+ return isCjkBase(uc) ?? (917760 <= uc && uc <= 917999);
16259
+ }
16260
+ function isNextCjk(uc) {
16261
+ return isCjkBase(uc) ?? !1;
16262
+ }
16263
+ function nonEmojiGeneralUseVS(uc) {
16264
+ return uc >= 65024 && uc <= 65038;
16265
+ }
16266
+ function markdownItCjkFriendlyPlugin(md) {
16267
+ let PreviousState = md.inline.State;
16268
+ class CjkFriendlyState extends PreviousState {
16269
+ scanDelims(start, canSplitWord) {
16270
+ let max = this.posMax, marker = this.src.charCodeAt(start), [lastChar2, lastCharPos] = getLastCharCode(this.src, start), lastMainChar = lastChar2, twoPrevChar = null;
16271
+ nonEmojiGeneralUseVS(lastChar2) && (twoPrevChar = getLastCharCode(this.src, lastCharPos)[0], /^\p{Zs}/u.test(String.fromCodePoint(twoPrevChar)) || (lastMainChar = twoPrevChar));
16272
+ let pos = start;
16273
+ for (; pos < max && this.src.charCodeAt(pos) === marker; )
16274
+ pos++;
16275
+ let count = pos - start, nextChar = pos < max ? this.src.codePointAt(pos) : 32, isLastWhiteSpace = md.utils.isWhiteSpace(lastMainChar), isNextWhiteSpace = md.utils.isWhiteSpace(nextChar);
16276
+ if (isLastWhiteSpace || isNextWhiteSpace)
16277
+ return {
16278
+ can_open: !isNextWhiteSpace,
16279
+ can_close: !isLastWhiteSpace,
16280
+ length: count
16281
+ };
16282
+ let isLastPunctChar = md.utils.isMdAsciiPunct(lastMainChar) || md.utils.isPunctChar(String.fromCodePoint(lastMainChar)), isNextPunctChar = md.utils.isMdAsciiPunct(nextChar) || md.utils.isPunctChar(String.fromCodePoint(nextChar)), left_flanking = isLastPunctChar, right_flanking = isNextPunctChar;
16283
+ if (canSplitWord) {
16284
+ let isEitherCJKChar = isNextCjk(nextChar) || (twoPrevChar !== null ? is2PreviousCjk(twoPrevChar, lastChar2) : isPreviousCjk(lastChar2));
16285
+ left_flanking || (left_flanking = isEitherCJKChar || !isNextPunctChar), right_flanking || (right_flanking = isEitherCJKChar || !isLastPunctChar);
16286
+ }
16287
+ return {
16288
+ can_open: left_flanking,
16289
+ can_close: right_flanking,
16290
+ length: count
16291
+ };
16292
+ function getLastCharCode(str, pos$1) {
16293
+ if (pos$1 <= 0)
16294
+ return [32, -1];
16295
+ let charCode = str.charCodeAt(pos$1 - 1);
16296
+ if ((charCode & 64512) !== 56320)
16297
+ return [charCode, pos$1 - 1];
16298
+ let codePoint = str.codePointAt(pos$1 - 2);
16299
+ return codePoint > 65535 ? [codePoint, pos$1 - 2] : [charCode, pos$1 - 1];
16300
+ }
16301
+ }
16302
+ }
16303
+ md.inline.State = CjkFriendlyState;
16304
+ }
16305
+ var decodeMap = /* @__PURE__ */ new Map([
15544
16306
  [0, 65533],
15545
16307
  [128, 8364],
15546
16308
  [130, 8218],
@@ -15862,7 +16624,7 @@ var htmlDecoder = /* @__PURE__ */ getDecoder(htmlDecodeTree);
15862
16624
  function decodeHTML(htmlString, mode = DecodingMode.Legacy) {
15863
16625
  return htmlDecoder(htmlString, mode);
15864
16626
  }
15865
- var import_markdown_it_task_checkbox = /* @__PURE__ */ __toESM2(require_markdown_it_task_checkbox(), 1), decodeCache = {};
16627
+ var decodeCache = {};
15866
16628
  function getDecodeCache(exclude) {
15867
16629
  let cache = decodeCache[exclude];
15868
16630
  if (cache)
@@ -18331,6 +19093,13 @@ var ParserInline = class {
18331
19093
  constructor() {
18332
19094
  __publicField(this, "ruler");
18333
19095
  __publicField(this, "ruler2");
19096
+ /**
19097
+ * State class used for inline parsing, mirroring `ParserInline.prototype.State` in
19098
+ * markdown-it. Plugins subclass it (`scanDelims`, `push`, `pushPending`, ...) and assign
19099
+ * the subclass back to `md.inline.State`; the parser then constructs it with
19100
+ * `new this.State(...)`.
19101
+ */
19102
+ __publicField(this, "State", StateInline);
18334
19103
  __publicField(this, "cachedRulesVersion", -1);
18335
19104
  __publicField(this, "cachedRules", []);
18336
19105
  __publicField(this, "cachedRules2Version", -1);
@@ -18437,13 +19206,20 @@ var ParserInline = class {
18437
19206
  isDefaultRuleset() {
18438
19207
  return this.ruler.version === this.defaultRulerVersion && this.ruler2.version === this.defaultRuler2Version;
18439
19208
  }
19209
+ /**
19210
+ * Whether inline parsing still uses the stock `StateInline`. The plain-text fast paths
19211
+ * construct no state at all, so they must stand down once a plugin replaces `State`.
19212
+ */
19213
+ usesDefaultState() {
19214
+ return this.State === StateInline;
19215
+ }
18440
19216
  parseSource(src, md, env, outTokens) {
18441
- if (typeof src == "string" && src.length > 0 && this.isDefaultRuleset() && isPlainInlineText$1(src)) {
19217
+ if (typeof src == "string" && src.length > 0 && this.isDefaultRuleset() && this.usesDefaultState() && isPlainInlineText$1(src)) {
18442
19218
  let token = new Token("text", "", 0);
18443
19219
  token.content = src, outTokens.push(token);
18444
19220
  return;
18445
19221
  }
18446
- let state = new StateInline(src, md, env, outTokens);
19222
+ let state = new this.State(src, md, env, outTokens);
18447
19223
  this.tokenize(state);
18448
19224
  let rules2 = this.getRules2(), len = rules2.length;
18449
19225
  if (!(state.env && (Object.prototype.hasOwnProperty.call(state.env, "__mdtsRuleProfile") || Object.prototype.hasOwnProperty.call(state.env, "__mdtsProfileRules")))) {
@@ -18470,7 +19246,7 @@ var ParserInline = class {
18470
19246
  }
18471
19247
  };
18472
19248
  function inline(state) {
18473
- let tokens = state.tokens, canUsePlainTextFastPath = !!state.md?.inline?.isDefaultRuleset?.();
19249
+ let tokens = state.tokens, inlineParser = state.md?.inline, canUsePlainTextFastPath = !!inlineParser?.isDefaultRuleset?.() && inlineParser?.usesDefaultState?.() !== !1;
18474
19250
  for (let i = 0, l = tokens.length; i < l; i++) {
18475
19251
  let tok = tokens[i];
18476
19252
  if (tok.type === "inline" && state.md) {
@@ -18484,6 +19260,30 @@ function inline(state) {
18484
19260
  }
18485
19261
  }
18486
19262
  var CJK_CHAR_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u, ASCII_DOMAIN_START_RE = /[0-9a-z]/i;
19263
+ function hasLinkifySeed(text$1) {
19264
+ return text$1.includes(".") || text$1.includes("@") || text$1.includes(":");
19265
+ }
19266
+ var linkifySeedSafety = /* @__PURE__ */ new WeakMap();
19267
+ function isLinkifySeedSafe(linkify$2) {
19268
+ let schemaSearch = linkify$2.re?.get_schema_search?.();
19269
+ if (!schemaSearch)
19270
+ return !1;
19271
+ let cached = linkifySeedSafety.get(linkify$2);
19272
+ if (cached && cached.schemaSearch === schemaSearch)
19273
+ return cached.safe;
19274
+ let schemas = linkify$2.__schemas__, safe = !0;
19275
+ if (schemas) {
19276
+ for (let name in schemas)
19277
+ if (name.charCodeAt(name.length - 1) !== 58) {
19278
+ safe = !1;
19279
+ break;
19280
+ }
19281
+ }
19282
+ return linkifySeedSafety.set(linkify$2, {
19283
+ schemaSearch,
19284
+ safe
19285
+ }), safe;
19286
+ }
18487
19287
  function isLinkOpen(str) {
18488
19288
  return /^<a[>\s]/i.test(str);
18489
19289
  }
@@ -18509,55 +19309,57 @@ function trimCjkPrefixFromFuzzyLink(linkify$2, link$1) {
18509
19309
  }
18510
19310
  function linkify(state) {
18511
19311
  let blockTokens = state.tokens;
18512
- if (state.md?.options?.linkify)
18513
- for (let j = 0; j < blockTokens.length; j++) {
18514
- let blockToken$1 = blockTokens[j];
18515
- if (blockToken$1.type !== "inline" || !state.md.linkify.test(blockToken$1.content))
19312
+ if (!state.md?.options?.linkify)
19313
+ return;
19314
+ let seedSafe = isLinkifySeedSafe(state.md.linkify), mayMatch = (text$1) => seedSafe ? hasLinkifySeed(text$1) : !0;
19315
+ for (let j = 0; j < blockTokens.length; j++) {
19316
+ let blockToken$1 = blockTokens[j];
19317
+ if (blockToken$1.type !== "inline" || !mayMatch(blockToken$1.content))
19318
+ continue;
19319
+ let tokens = blockToken$1.children;
19320
+ tokens || (tokens = [], blockToken$1.children = tokens);
19321
+ let htmlLinkLevel = 0;
19322
+ for (let i = tokens.length - 1; i >= 0; i--) {
19323
+ let currentToken = tokens[i];
19324
+ if (currentToken.type === "link_close") {
19325
+ for (i--; i >= 0 && tokens[i].level !== currentToken.level && tokens[i].type !== "link_open"; )
19326
+ i--;
18516
19327
  continue;
18517
- let tokens = blockToken$1.children;
18518
- tokens || (tokens = [], blockToken$1.children = tokens);
18519
- let htmlLinkLevel = 0;
18520
- for (let i = tokens.length - 1; i >= 0; i--) {
18521
- let currentToken = tokens[i];
18522
- if (currentToken.type === "link_close") {
18523
- for (i--; i >= 0 && tokens[i].level !== currentToken.level && tokens[i].type !== "link_open"; )
18524
- i--;
19328
+ }
19329
+ if (currentToken.type === "html_inline" && (isLinkOpen(currentToken.content) && htmlLinkLevel > 0 && htmlLinkLevel--, isLinkClose(currentToken.content) && htmlLinkLevel++), htmlLinkLevel > 0 || currentToken.type !== "text" || !mayMatch(currentToken.content))
19330
+ continue;
19331
+ let text$1 = currentToken.content, links = (state.md.linkify.match(text$1) || []).map((link$1) => trimCjkPrefixFromFuzzyLink(state.md.linkify, link$1));
19332
+ if (links.length === 0)
19333
+ continue;
19334
+ let nodes = [], level = currentToken.level, lastPos = 0;
19335
+ links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === "text_special" && (links = links.slice(1));
19336
+ for (let ln = 0; ln < links.length; ln++) {
19337
+ let link$1 = links[ln], fullUrl = state.md.normalizeLink(link$1.url);
19338
+ if (!state.md.validateLink(fullUrl))
18525
19339
  continue;
19340
+ let urlText = link$1.text;
19341
+ link$1.schema ? link$1.schema === "mailto:" && !/^mailto:/i.test(urlText) ? urlText = state.md.normalizeLinkText(`mailto:${urlText}`).replace(/^mailto:/, "") : urlText = state.md.normalizeLinkText(urlText) : urlText = state.md.normalizeLinkText(`http://${urlText}`).replace(/^http:\/\//, "");
19342
+ let pos = link$1.index;
19343
+ if (pos > lastPos) {
19344
+ let textToken$1 = new Token("text", "", 0);
19345
+ textToken$1.content = text$1.slice(lastPos, pos), textToken$1.level = level, nodes.push(textToken$1);
18526
19346
  }
18527
- if (currentToken.type === "html_inline" && (isLinkOpen(currentToken.content) && htmlLinkLevel > 0 && htmlLinkLevel--, isLinkClose(currentToken.content) && htmlLinkLevel++), htmlLinkLevel > 0 || currentToken.type !== "text" || !state.md.linkify.test(currentToken.content))
18528
- continue;
18529
- let text$1 = currentToken.content, links = (state.md.linkify.match(text$1) || []).map((link$1) => trimCjkPrefixFromFuzzyLink(state.md.linkify, link$1));
18530
- if (links.length === 0)
18531
- continue;
18532
- let nodes = [], level = currentToken.level, lastPos = 0;
18533
- links.length > 0 && links[0].index === 0 && i > 0 && tokens[i - 1].type === "text_special" && (links = links.slice(1));
18534
- for (let ln = 0; ln < links.length; ln++) {
18535
- let link$1 = links[ln], fullUrl = state.md.normalizeLink(link$1.url);
18536
- if (!state.md.validateLink(fullUrl))
18537
- continue;
18538
- let urlText = link$1.text;
18539
- link$1.schema ? link$1.schema === "mailto:" && !/^mailto:/i.test(urlText) ? urlText = state.md.normalizeLinkText(`mailto:${urlText}`).replace(/^mailto:/, "") : urlText = state.md.normalizeLinkText(urlText) : urlText = state.md.normalizeLinkText(`http://${urlText}`).replace(/^http:\/\//, "");
18540
- let pos = link$1.index;
18541
- if (pos > lastPos) {
18542
- let textToken$1 = new Token("text", "", 0);
18543
- textToken$1.content = text$1.slice(lastPos, pos), textToken$1.level = level, nodes.push(textToken$1);
18544
- }
18545
- let tokenOpen = new Token("link_open", "a", 1);
18546
- tokenOpen.attrs = [["href", fullUrl]], tokenOpen.level = level++, tokenOpen.markup = "linkify", tokenOpen.info = "auto", nodes.push(tokenOpen);
18547
- let tokenText = new Token("text", "", 0);
18548
- tokenText.content = urlText, tokenText.level = level, nodes.push(tokenText);
18549
- let tokenClose = new Token("link_close", "a", -1);
18550
- tokenClose.level = --level, tokenClose.markup = "linkify", tokenClose.info = "auto", nodes.push(tokenClose), lastPos = link$1.lastIndex;
18551
- }
18552
- if (lastPos !== 0) {
18553
- if (lastPos < text$1.length) {
18554
- let textToken$1 = new Token("text", "", 0);
18555
- textToken$1.content = text$1.slice(lastPos), textToken$1.level = level, nodes.push(textToken$1);
18556
- }
18557
- tokens.splice(i, 1, ...nodes);
19347
+ let tokenOpen = new Token("link_open", "a", 1);
19348
+ tokenOpen.attrs = [["href", fullUrl]], tokenOpen.level = level++, tokenOpen.markup = "linkify", tokenOpen.info = "auto", nodes.push(tokenOpen);
19349
+ let tokenText = new Token("text", "", 0);
19350
+ tokenText.content = urlText, tokenText.level = level, nodes.push(tokenText);
19351
+ let tokenClose = new Token("link_close", "a", -1);
19352
+ tokenClose.level = --level, tokenClose.markup = "linkify", tokenClose.info = "auto", nodes.push(tokenClose), lastPos = link$1.lastIndex;
19353
+ }
19354
+ if (lastPos !== 0) {
19355
+ if (lastPos < text$1.length) {
19356
+ let textToken$1 = new Token("text", "", 0);
19357
+ textToken$1.content = text$1.slice(lastPos), textToken$1.level = level, nodes.push(textToken$1);
18558
19358
  }
19359
+ tokens.splice(i, 1, ...nodes);
18559
19360
  }
18560
19361
  }
19362
+ }
18561
19363
  }
18562
19364
  var NEWLINES_RE = /\r\n?|\n/g, NULL_RE = /\0/g;
18563
19365
  function normalize(state) {
@@ -18733,7 +19535,7 @@ function process_inlines(tokens, state) {
18733
19535
  nextChar = tokens[j].content.charCodeAt(0);
18734
19536
  break;
18735
19537
  }
18736
- let isLastPunctChar = isMdAsciiPunct(lastChar2) || isPunctChar(String.fromCharCode(lastChar2)), isNextPunctChar = isMdAsciiPunct(nextChar) || isPunctChar(String.fromCharCode(nextChar)), isLastWhiteSpace = isWhiteSpace(lastChar2), isNextWhiteSpace = isWhiteSpace(nextChar);
19538
+ let isLastPunctChar = isPunctCode(lastChar2), isNextPunctChar = isPunctCode(nextChar), isLastWhiteSpace = isWhiteSpace(lastChar2), isNextWhiteSpace = isWhiteSpace(nextChar);
18737
19539
  if (isNextWhiteSpace ? canOpen = !1 : isNextPunctChar && (isLastWhiteSpace || isLastPunctChar || (canOpen = !1)), isLastWhiteSpace ? canClose = !1 : isLastPunctChar && (isNextWhiteSpace || isNextPunctChar || (canClose = !1)), nextChar === 34 && t[0] === '"' && lastChar2 >= 48 && lastChar2 <= 57 && (canClose = canOpen = !1), canOpen && canClose && (canOpen = isLastPunctChar, canClose = isNextPunctChar), !canOpen && !canClose) {
18738
19540
  isSingle && (token.content = replaceAt(token.content, t.index, APOSTROPHE));
18739
19541
  continue;
@@ -18788,28 +19590,30 @@ var BAD_PROTO_RE = /^(?:vbscript|javascript|file|data):/, GOOD_DATA_RE = /^data:
18788
19590
  "http:",
18789
19591
  "https:",
18790
19592
  "mailto:"
18791
- ];
19593
+ ], NON_ASCII_RE = /[^\0-\x7F]/, PUNYCODE_LABEL_RE = /xn--/, ENCODE_IDENTITY_RE = /%(?![0-9a-f]{2})|[^\w;/?:@&=+$,\-.!~*'()#%]/i, DECODE_SCAN_RE = /%[0-9a-f]{2}/i;
18792
19594
  function validateLink(url) {
18793
19595
  let str = url.trim().toLowerCase();
18794
19596
  return BAD_PROTO_RE.test(str) ? GOOD_DATA_RE.test(str) : !0;
18795
19597
  }
18796
19598
  function normalizeLink(url) {
18797
19599
  let parsed = parse_default(url, !0);
18798
- if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)))
19600
+ if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)) && NON_ASCII_RE.test(parsed.hostname))
18799
19601
  try {
18800
19602
  parsed.hostname = import_punycode.default.toASCII(parsed.hostname);
18801
19603
  } catch {
18802
19604
  }
18803
- return encode_default(format(parsed));
19605
+ let formatted = format(parsed);
19606
+ return ENCODE_IDENTITY_RE.test(formatted) ? encode_default(formatted) : formatted;
18804
19607
  }
18805
19608
  function normalizeLinkText(url) {
18806
19609
  let parsed = parse_default(url, !0);
18807
- if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)))
19610
+ if (parsed.hostname && (!parsed.protocol || RECODE_HOSTNAME_FOR.includes(parsed.protocol)) && (NON_ASCII_RE.test(parsed.hostname) || PUNYCODE_LABEL_RE.test(parsed.hostname)))
18808
19611
  try {
18809
19612
  parsed.hostname = import_punycode.default.toUnicode(parsed.hostname);
18810
19613
  } catch {
18811
19614
  }
18812
- return decode_default(format(parsed), `${decode_default.defaultChars}%`);
19615
+ let formatted = format(parsed);
19616
+ return DECODE_SCAN_RE.test(formatted) ? decode_default(formatted, `${decode_default.defaultChars}%`) : formatted;
18813
19617
  }
18814
19618
  function isSpace$7(code$1) {
18815
19619
  switch (code$1) {
@@ -22208,6 +23012,37 @@ var Renderer = class {
22208
23012
  return output;
22209
23013
  }
22210
23014
  }, renderer_default = Renderer, EMPTY_TOKENS = [], GLOBAL_STATE_APPEND_SCAN_WINDOW = 4096;
23015
+ function copyOptions(options) {
23016
+ let copy = { ...options };
23017
+ return Array.isArray(options.quotes) && (copy.quotes = [...options.quotes]), options.experimental && (copy.experimental = { ...options.experimental }), copy;
23018
+ }
23019
+ function optionsEqual(left, right) {
23020
+ let keys = Object.keys(right);
23021
+ return Object.keys(left).length !== keys.length ? !1 : keys.every((key) => {
23022
+ if (!Object.hasOwn(left, key))
23023
+ return !1;
23024
+ let leftValue = left[key], rightValue = right[key];
23025
+ if (Array.isArray(leftValue) && Array.isArray(rightValue))
23026
+ return leftValue.length === rightValue.length && leftValue.every((value, index) => Object.is(value, rightValue[index]));
23027
+ if (key === "experimental" && leftValue && rightValue) {
23028
+ let leftExperimental = leftValue, rightExperimental = rightValue, experimentalKeys = Object.keys(rightExperimental);
23029
+ return Object.keys(leftExperimental).length === experimentalKeys.length && experimentalKeys.every((option) => Object.hasOwn(leftExperimental, option) && Object.is(leftExperimental[option], rightExperimental[option]));
23030
+ }
23031
+ return Object.is(leftValue, rightValue);
23032
+ });
23033
+ }
23034
+ function copyParserConfig(md) {
23035
+ return {
23036
+ options: copyOptions(md.options),
23037
+ coreVersion: md.core.ruler.version,
23038
+ blockVersion: md.block.ruler.version,
23039
+ inlineVersion: md.inline.ruler.version,
23040
+ inline2Version: md.inline.ruler2.version
23041
+ };
23042
+ }
23043
+ function parserConfigEqual(config$1, md) {
23044
+ return optionsEqual(config$1.options, md.options) && config$1.coreVersion === md.core.ruler.version && config$1.blockVersion === md.block.ruler.version && config$1.inlineVersion === md.inline.ruler.version && config$1.inline2Version === md.inline.ruler2.version;
23045
+ }
22211
23046
  function appendedHasBlockConstructs(s) {
22212
23047
  let len = s.length, lineStart = 0;
22213
23048
  for (; lineStart <= len; ) {
@@ -22350,9 +23185,9 @@ var StreamParser = class {
22350
23185
  __publicField(this, "core");
22351
23186
  __publicField(this, "anchorBlock", new ParserBlock());
22352
23187
  __publicField(this, "cache", null);
23188
+ __publicField(this, "snapshots", /* @__PURE__ */ new WeakSet());
22353
23189
  __publicField(this, "stats", makeEmptyStats());
22354
23190
  __publicField(this, "normalizeLineEndings", !0);
22355
- __publicField(this, "coreRulerVersion", -1);
22356
23191
  __publicField(this, "tokenMapsTrusted", !0);
22357
23192
  __publicField(this, "allowUntrustedTailReuse", !1);
22358
23193
  __publicField(this, "MIN_SIZE_FOR_OPTIMIZATION", 1e3);
@@ -22375,19 +23210,46 @@ var StreamParser = class {
22375
23210
  let { resets } = this.stats;
22376
23211
  this.stats = makeEmptyStats(), this.stats.resets = resets;
22377
23212
  }
22378
- parse(src, env, md) {
22379
- let priorEnv = this.cache?.env;
22380
- this.coreRulerVersion >= 0 && this.coreRulerVersion !== md.core.ruler.version && (this.cache = null), this.coreRulerVersion = md.core.ruler.version;
22381
- let coreRules = md.core.ruler.getNamedRules(""), lineNormalizerIndex = coreRules.findIndex((rule) => rule.fn === normalize), blockRuleIndex = coreRules.findIndex((rule) => rule.fn === block), namedNormalizeRule = coreRules.find((rule) => rule.name === "normalize");
23213
+ snapshot() {
23214
+ let cache = this.cache;
23215
+ if (!cache)
23216
+ return null;
23217
+ let state = cache.snapshotState ?? { cache };
23218
+ cache.snapshotState = state;
23219
+ let snapshot = {
23220
+ state,
23221
+ get sourceLength() {
23222
+ return this.state.cache.src.length;
23223
+ },
23224
+ get tokenCount() {
23225
+ return this.state.cache.tokens.length;
23226
+ }
23227
+ };
23228
+ return this.snapshots.add(snapshot), snapshot;
23229
+ }
23230
+ restore(snapshot, md) {
23231
+ if (!this.snapshots.has(snapshot))
23232
+ throw new TypeError("Invalid stream snapshot");
23233
+ let cache = snapshot.state.cache;
23234
+ return this.cache = cache, parserConfigEqual(cache.config, md) ? cache.tokens : this.parse(cache.src, cache.env, md);
23235
+ }
23236
+ append(segment, env, md) {
23237
+ let cached = this.cache;
23238
+ if (!cached)
23239
+ throw new Error("Stream append requires cached history; call stream.parse(fullSource) first");
23240
+ return this.ensureBoundaryState(cached), this.parse(cached.src + segment, env, md, segment);
23241
+ }
23242
+ parse(src, env, md, knownAppend) {
23243
+ let previousCache = this.cache, priorEnv = previousCache?.env, coreRules = md.core.ruler.getNamedRules(""), lineNormalizerIndex = coreRules.findIndex((rule) => rule.fn === normalize), blockRuleIndex = coreRules.findIndex((rule) => rule.fn === block), namedNormalizeRule = coreRules.find((rule) => rule.name === "normalize");
22382
23244
  this.normalizeLineEndings = lineNormalizerIndex >= 0 && blockRuleIndex >= 0 && lineNormalizerIndex < blockRuleIndex;
22383
- let envProvided = env, previousCache = this.cache, customNormalize = namedNormalizeRule && namedNormalizeRule.fn !== normalize, nonstandardBuiltinNormalize = namedNormalizeRule && !this.normalizeLineEndings && src.includes("\r"), unknownPreBlockRule = blockRuleIndex < 0 || coreRules.slice(0, blockRuleIndex).some((rule) => rule.fn !== normalize);
23245
+ let envProvided = env, configChanged = !!previousCache && !parserConfigEqual(previousCache.config, md), customNormalize = namedNormalizeRule && namedNormalizeRule.fn !== normalize, nonstandardBuiltinNormalize = namedNormalizeRule && !this.normalizeLineEndings && src.includes("\r"), unknownPreBlockRule = blockRuleIndex < 0 || coreRules.slice(0, blockRuleIndex).some((rule) => rule.fn !== normalize);
22384
23246
  this.tokenMapsTrusted = !(blockRuleIndex < 0 || coreRules.slice(blockRuleIndex + 1).some((rule) => rule.fn !== inline && rule.fn !== linkify && rule.fn !== replacements && rule.fn !== smartquotes && rule.fn !== text_join)), this.allowUntrustedTailReuse = this.tokenMapsTrusted || md.options?.streamTailLocalPostBlockRules === !0;
22385
- let cached = customNormalize || nonstandardBuiltinNormalize || unknownPreBlockRule ? null : previousCache;
23247
+ let cached = configChanged || customNormalize || nonstandardBuiltinNormalize || unknownPreBlockRule ? null : previousCache;
22386
23248
  if (beginParseDiagnostics(envProvided ?? previousCache?.env ?? priorEnv), !cached || envProvided && envProvided !== cached.env) {
22387
23249
  let workingEnv = envProvided ?? previousCache?.env ?? priorEnv ?? {}, explicitChunkFallbackSetting$1 = !!md.__explicitStreamChunkFallbackSetting, canImplicitLargeInput$1 = typeof md.__canUseImplicitLargeInputStrategy == "function" ? md.__canUseImplicitLargeInputStrategy() : !0, wantsChunking$1 = !!md.options?.streamChunkedFallback, allowImplicitChunk$1 = !explicitChunkFallbackSetting$1 && canImplicitLargeInput$1, chunkedEnabled$1 = wantsChunking$1 || allowImplicitChunk$1, chunkAdaptive$1 = md.options?.streamChunkAdaptive !== !1, targetChunks$1 = md.options?.streamChunkTargetChunks ?? 8, chunkSizeCharsCfg$1 = md.options?.streamChunkSizeChars, chunkSizeLinesCfg$1 = md.options?.streamChunkSizeLines, chunkMaxChunksCfg$1 = md.options?.streamChunkMaxChunks, explicitChunkConfig$1 = !!md.__explicitStreamChunkConfig, auto$1 = md.options?.autoTuneChunks !== !1, chunkFenceAware$1 = md.options?.streamChunkFenceAware ?? !0, largeCachePolicy = md.options?.streamLargeCachePolicy ?? "retain", skipCacheChars = md.options?.streamSkipCacheAboveChars ?? this.DEFAULT_SKIP_CACHE_CHARS, skipCacheLines = md.options?.streamSkipCacheAboveLines ?? this.DEFAULT_SKIP_CACHE_LINES, srcLineCount, shouldSkipLargeCache = !1;
22388
- if (largeCachePolicy === "skip" && (shouldSkipLargeCache = src.length >= skipCacheChars, !shouldSkipLargeCache && skipCacheLines !== void 0 && (srcLineCount = countLines(src), shouldSkipLargeCache = srcLineCount >= skipCacheLines)), shouldSkipLargeCache) {
23250
+ if (largeCachePolicy === "skip" && (shouldSkipLargeCache = src.length >= skipCacheChars, !shouldSkipLargeCache && skipCacheLines !== void 0 && (srcLineCount = countLines(src), shouldSkipLargeCache = srcLineCount >= skipCacheLines)), shouldSkipLargeCache && knownAppend === void 0 && !previousCache?.snapshotState) {
22389
23251
  let parsed$2 = this.parseFullDocument(src, workingEnv, md, srcLineCount, !1);
22390
- return this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
23252
+ return this.cache = null, this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
22391
23253
  area: "stream",
22392
23254
  path: "stream-full",
22393
23255
  reason: "skip-cache-large-one-shot",
@@ -22403,26 +23265,28 @@ var StreamParser = class {
22403
23265
  maxChunkLines: useLines,
22404
23266
  fenceAware: recommendation?.fenceAware ?? chunkFenceAware$1,
22405
23267
  maxChunks: useMaxChunks
22406
- });
22407
- return this.cache = {
23268
+ }), globalStateReason = getParseDiagnostics(workingEnv)?.chunk?.globalStateDetected ?? null, cache$2 = this.setCache({
22408
23269
  src,
22409
23270
  tokens,
22410
23271
  env: workingEnv,
22411
23272
  lineCount: srcLineCount,
22412
23273
  lastSegment: void 0,
22413
- globalStateReason: detectGlobalMarkdownState(src)
22414
- }, this.updateCacheLineCount(this.cache, srcLineCount), this.recordChunkedParseResult(workingEnv, wantsChunking$1 ? "explicit-initial-large-doc" : "default-initial-large-doc"), tokens;
23274
+ globalStateReason
23275
+ }, md);
23276
+ return this.updateCacheLineCount(cache$2, srcLineCount), this.recordChunkedParseResult(workingEnv, wantsChunking$1 ? "explicit-initial-large-doc" : "default-initial-large-doc"), tokens;
22415
23277
  }
22416
23278
  }
22417
23279
  let parsed$1 = this.parseFullDocument(src, workingEnv, md, srcLineCount);
22418
- return srcLineCount = parsed$1.lineCount, this.cache = {
23280
+ srcLineCount = parsed$1.lineCount;
23281
+ let cache$1 = this.setCache({
22419
23282
  src,
22420
23283
  tokens: parsed$1.tokens,
22421
23284
  env: workingEnv,
22422
23285
  lineCount: srcLineCount,
22423
23286
  lastSegment: void 0,
22424
- globalStateReason: detectGlobalMarkdownState(src)
22425
- }, this.updateCacheLineCount(this.cache, srcLineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
23287
+ globalStateReason: parsed$1.globalStateReason
23288
+ }, md);
23289
+ return this.updateCacheLineCount(cache$1, srcLineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(workingEnv, {
22426
23290
  area: "stream",
22427
23291
  path: "stream-full",
22428
23292
  reason: "initial-parse",
@@ -22435,21 +23299,21 @@ var StreamParser = class {
22435
23299
  path: "stream-cache",
22436
23300
  reason: "same-source"
22437
23301
  }), cached.tokens;
22438
- let appendDelta = src.startsWith(cached.src) ? src.slice(cached.src.length) : null, cachedGlobalStateReason = cached.globalStateReason;
23302
+ let appendDelta = knownAppend !== void 0 ? knownAppend : src.startsWith(cached.src) ? src.slice(cached.src.length) : null, cachedGlobalStateReason = cached.globalStateReason;
22439
23303
  cachedGlobalStateReason === void 0 && (cachedGlobalStateReason = detectGlobalMarkdownState(cached.src), cached.globalStateReason = cachedGlobalStateReason);
22440
23304
  let currentGlobalStateReason = cachedGlobalStateReason ? null : appendDelta !== null ? this.detectGlobalStateForAppend(cached, appendDelta) : detectGlobalMarkdownState(src), nextGlobalStateReason = cachedGlobalStateReason || currentGlobalStateReason;
22441
23305
  if (nextGlobalStateReason) {
22442
23306
  let fallbackEnv$1 = envProvided ?? cached.env;
22443
23307
  resetKnownGlobalMarkdownState(fallbackEnv$1);
22444
- let fallbackGlobalStateReason = detectGlobalMarkdownState(src), parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount;
22445
- return this.cache = {
23308
+ let parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount, cache$1 = this.setCache({
22446
23309
  src,
22447
23310
  tokens: nextTokens$1,
22448
23311
  env: fallbackEnv$1,
22449
23312
  lineCount,
22450
23313
  lastSegment: void 0,
22451
- globalStateReason: fallbackGlobalStateReason
22452
- }, this.updateCacheLineCount(this.cache, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
23314
+ globalStateReason: parsed$1.globalStateReason
23315
+ }, md);
23316
+ return this.updateCacheLineCount(cache$1, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
22453
23317
  area: "stream",
22454
23318
  path: "stream-full",
22455
23319
  reason: `global-state:${nextGlobalStateReason}`,
@@ -22457,23 +23321,23 @@ var StreamParser = class {
22457
23321
  }), nextTokens$1;
22458
23322
  }
22459
23323
  let threshold = md.options?.streamOptimizationMinSize ?? this.MIN_SIZE_FOR_OPTIMIZATION;
22460
- if (cached.src.length < threshold && src.length < threshold * 1.5 && !src.startsWith(cached.src)) {
22461
- let fallbackEnv$1 = envProvided ?? cached.env, parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount;
22462
- return this.cache = {
23324
+ if (cached.src.length < threshold && src.length < threshold * 1.5 && appendDelta === null) {
23325
+ let fallbackEnv$1 = envProvided ?? cached.env, parsed$1 = this.parseFullDocument(src, fallbackEnv$1, md), nextTokens$1 = parsed$1.tokens, lineCount = parsed$1.lineCount, cache$1 = this.setCache({
22463
23326
  src,
22464
23327
  tokens: nextTokens$1,
22465
23328
  env: fallbackEnv$1,
22466
23329
  lineCount,
22467
23330
  lastSegment: void 0,
22468
- globalStateReason: detectGlobalMarkdownState(src)
22469
- }, this.updateCacheLineCount(this.cache, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
23331
+ globalStateReason: parsed$1.globalStateReason
23332
+ }, md);
23333
+ return this.updateCacheLineCount(cache$1, lineCount), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv$1, {
22470
23334
  area: "stream",
22471
23335
  path: "stream-full",
22472
23336
  reason: "small-non-append",
22473
23337
  unbounded: !!getParseDiagnostics(fallbackEnv$1)?.unbounded
22474
23338
  }), nextTokens$1;
22475
23339
  }
22476
- let cachedLastSegment = this.ensureLastSegment(cached), verifiedUntrustedTail = this.tokenMapsTrusted || this.allowUntrustedTailReuse && (cached.lastSegmentVerified === !0 || !!(cachedLastSegment && this.hasVerifiedSegmentAnchor(cached, cachedLastSegment, md))), appended = appendDelta !== null && this.shouldPreferTailReparseForAppend(cached, verifiedUntrustedTail) || !this.tokenMapsTrusted ? null : this.getAppendedSegment(cached, src, appendDelta);
23340
+ let cachedLastSegment = this.ensureLastSegment(cached, knownAppend !== void 0), verifiedUntrustedTail = this.tokenMapsTrusted || this.allowUntrustedTailReuse && (cached.lastSegmentVerified === !0 || !!(cachedLastSegment && this.hasVerifiedSegmentAnchor(cached, cachedLastSegment, md))), appended = appendDelta !== null && this.shouldPreferTailReparseForAppend(cached, verifiedUntrustedTail) || !this.tokenMapsTrusted ? null : this.getAppendedSegment(cached, src, appendDelta);
22477
23341
  if (appended) {
22478
23342
  let cachedLineCount = cached.lineCount ?? countLines(cached.src), ctxLines = 3;
22479
23343
  appended.length > 5e3 ? ctxLines = 8 : appended.length > 1e3 ? ctxLines = 6 : appended.length > 200 && (ctxLines = 4), ctxLines = Math.min(ctxLines, cachedLineCount);
@@ -22548,11 +23412,16 @@ var StreamParser = class {
22548
23412
  }
22549
23413
  dup > 0 && (appendedTokenStart += dup), a.length > appendedTokenStart && this.appendTokens(cached.tokens, a, appendedTokenStart);
22550
23414
  }
22551
- if (this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.globalStateReason = null, cached.lineCount = cachedLineCount + (appendedLineCount ?? countAppendedLines()), cached.tokens.length > appendStart) {
23415
+ if (cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.globalStateReason = null, cached.lineCount = cachedLineCount + (appendedLineCount ?? countAppendedLines()), cached.tokens.length > appendStart) {
22552
23416
  let appendedLastSegment = this.getLastSegment(cached.tokens, src, appendStart, cached.tokens.length, src.length - appended.length, cachedLineCount);
22553
- appendedLastSegment ? cached.lastSegment = appendedLastSegment : cached.lastSegment = void 0;
23417
+ if (appendedLastSegment) {
23418
+ cached.lastSegment = appendedLastSegment;
23419
+ let appendedOffset = src.length - appended.length;
23420
+ cached.lastSegmentSource = appended.slice(Math.max(0, appendedLastSegment.srcOffset - appendedOffset));
23421
+ } else
23422
+ cached.lastSegment = void 0, cached.lastSegmentSource = void 0;
22554
23423
  } else
22555
- cached.lastSegment = void 0;
23424
+ cached.lastSegment = void 0, cached.lastSegmentSource = void 0;
22556
23425
  return cached.lastSegmentVerified = void 0, this.stats.total += 1, this.stats.appendHits += 1, useUnboundedAppend && (this.stats.unboundedAppendHits = (this.stats.unboundedAppendHits || 0) + 1), this.stats.lastMode = "append", setStrategyDiagnostics(cached.env, {
22557
23426
  area: "stream",
22558
23427
  path: useUnboundedAppend ? "stream-unbounded-append" : "stream-append",
@@ -22560,7 +23429,7 @@ var StreamParser = class {
22560
23429
  unbounded: useUnboundedAppend
22561
23430
  }), cached.tokens;
22562
23431
  }
22563
- let fallbackEnv = envProvided ?? cached.env, tailReparsed = verifiedUntrustedTail ? this.tryTailSegmentReparse(src, cached, fallbackEnv, md, cachedLastSegment ?? void 0) : this.allowUntrustedTailReuse ? this.tryUntrustedParagraphTailReparse(src, cached, fallbackEnv, md) : null;
23432
+ let fallbackEnv = envProvided ?? cached.env, tailReparsed = verifiedUntrustedTail ? this.tryTailSegmentReparse(src, cached, fallbackEnv, md, cachedLastSegment ?? void 0, appendDelta ?? void 0) : this.allowUntrustedTailReuse ? this.tryUntrustedParagraphTailReparse(src, cached, fallbackEnv, md) : null;
22564
23433
  if (tailReparsed)
22565
23434
  return this.stats.total += 1, this.stats.tailHits += 1, this.stats.lastMode = "tail", setStrategyDiagnostics(fallbackEnv, {
22566
23435
  area: "stream",
@@ -22577,26 +23446,28 @@ var StreamParser = class {
22577
23446
  maxChunkLines: useLines,
22578
23447
  fenceAware: recommendation?.fenceAware ?? chunkFenceAware,
22579
23448
  maxChunks: useMaxChunks
22580
- });
22581
- return this.cache = {
23449
+ }), globalStateReason = getParseDiagnostics(fallbackEnv)?.chunk?.globalStateDetected ?? null, cache$1 = this.setCache({
22582
23450
  src,
22583
23451
  tokens,
22584
23452
  env: fallbackEnv,
22585
23453
  lineCount: srcLineCount2,
22586
23454
  lastSegment: void 0,
22587
- globalStateReason: detectGlobalMarkdownState(src)
22588
- }, this.updateCacheLineCount(this.cache, srcLineCount2), this.recordChunkedParseResult(fallbackEnv, wantsChunking ? "explicit-fallback-large-doc" : "default-fallback-large-doc"), tokens;
23455
+ globalStateReason
23456
+ }, md);
23457
+ return this.updateCacheLineCount(cache$1, srcLineCount2), this.recordChunkedParseResult(fallbackEnv, wantsChunking ? "explicit-fallback-large-doc" : "default-fallback-large-doc"), tokens;
22589
23458
  }
22590
23459
  }
22591
23460
  let parsed = this.parseFullDocument(src, fallbackEnv, md, srcLineCount2), nextTokens = parsed.tokens;
22592
- return srcLineCount2 = parsed.lineCount, this.cache = {
23461
+ srcLineCount2 = parsed.lineCount;
23462
+ let cache = this.setCache({
22593
23463
  src,
22594
23464
  tokens: nextTokens,
22595
23465
  env: fallbackEnv,
22596
23466
  lineCount: srcLineCount2,
22597
23467
  lastSegment: void 0,
22598
- globalStateReason: detectGlobalMarkdownState(src)
22599
- }, this.updateCacheLineCount(this.cache, srcLineCount2), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv, {
23468
+ globalStateReason: parsed.globalStateReason
23469
+ }, md);
23470
+ return this.updateCacheLineCount(cache, srcLineCount2), this.stats.total += 1, this.stats.fullParses += 1, this.stats.lastMode = "full", setStrategyDiagnostics(fallbackEnv, {
22600
23471
  area: "stream",
22601
23472
  path: "stream-full",
22602
23473
  reason: "fallback-full",
@@ -22622,11 +23493,10 @@ var StreamParser = class {
22622
23493
  });
22623
23494
  }
22624
23495
  parseFullDocument(src, env, md, knownLineCount, needLineCount = !0) {
22625
- let currentGlobalStateReason = detectGlobalMarkdownState(src);
22626
23496
  getKnownGlobalMarkdownState(env) && resetKnownGlobalMarkdownState(env);
22627
23497
  let autoUnboundedDecision = typeof md.__canUseImplicitLargeInputStrategy != "function" || md.__canUseImplicitLargeInputStrategy() ? getAutoUnboundedDecision(md, src.length, knownLineCount) : "no";
22628
23498
  if (autoUnboundedDecision === "yes") {
22629
- let tokens = parseStringUnbounded(md, src, env);
23499
+ let tokens = parseStringUnbounded(md, src, env), globalStateReason = getParseDiagnostics(env)?.unbounded?.globalStateDetected ?? null;
22630
23500
  return setStrategyDiagnostics(env, {
22631
23501
  area: "stream",
22632
23502
  path: "stream-full",
@@ -22634,12 +23504,13 @@ var StreamParser = class {
22634
23504
  unbounded: !0
22635
23505
  }), {
22636
23506
  tokens,
22637
- lineCount: knownLineCount ?? (needLineCount ? countLines(src) : 0)
23507
+ lineCount: knownLineCount ?? (needLineCount ? countLines(src) : 0),
23508
+ globalStateReason
22638
23509
  };
22639
23510
  }
22640
23511
  let lineCount = knownLineCount;
22641
23512
  if (autoUnboundedDecision === "need-lines" && (lineCount = countLines(src), shouldAutoUseUnbounded(md, src.length, lineCount))) {
22642
- let tokens = parseStringUnbounded(md, src, env);
23513
+ let tokens = parseStringUnbounded(md, src, env), globalStateReason = getParseDiagnostics(env)?.unbounded?.globalStateDetected ?? null;
22643
23514
  return setStrategyDiagnostics(env, {
22644
23515
  area: "stream",
22645
23516
  path: "stream-full",
@@ -22647,12 +23518,16 @@ var StreamParser = class {
22647
23518
  unbounded: !0
22648
23519
  }), {
22649
23520
  tokens,
22650
- lineCount
23521
+ lineCount,
23522
+ globalStateReason
22651
23523
  };
22652
23524
  }
22653
- return lineCount === void 0 && (lineCount = needLineCount ? countLines(src) : 0), {
23525
+ lineCount === void 0 && (lineCount = needLineCount ? countLines(src) : 0);
23526
+ let currentGlobalStateReason = detectGlobalMarkdownState(src);
23527
+ return {
22654
23528
  tokens: runWithKnownGlobalMarkdownState(env, currentGlobalStateReason, () => this.core.parse(src, env, md).tokens),
22655
- lineCount
23529
+ lineCount,
23530
+ globalStateReason: currentGlobalStateReason
22656
23531
  };
22657
23532
  }
22658
23533
  shouldUseUnboundedAppend(src, _cached, appended) {
@@ -22660,8 +23535,8 @@ var StreamParser = class {
22660
23535
  }
22661
23536
  getAppendedSegment(cache, next, knownAppend) {
22662
23537
  let prev = cache.src;
22663
- if (knownAppend === null || knownAppend === void 0 && !next.startsWith(prev) || !prev.endsWith(`
22664
- `))
23538
+ if (knownAppend === null || knownAppend === void 0 && !next.startsWith(prev) || (knownAppend !== void 0 ? !this.ensureBoundaryState(cache).endsWithNewline : !prev.endsWith(`
23539
+ `)))
22665
23540
  return null;
22666
23541
  let segment = knownAppend ?? next.slice(prev.length);
22667
23542
  if (!segment)
@@ -22678,47 +23553,69 @@ var StreamParser = class {
22678
23553
  if (trimmedFirstLine.length === 0)
22679
23554
  return null;
22680
23555
  if (/^[-=]+$/.test(trimmedFirstLine)) {
22681
- let prevWithoutTrailingNewline = prev.slice(0, -1), lastBreak = prevWithoutTrailingNewline.lastIndexOf(`
23556
+ let previousLineNonBlank;
23557
+ if (knownAppend !== void 0)
23558
+ previousLineNonBlank = this.ensureBoundaryState(cache).previousLineNonBlank;
23559
+ else {
23560
+ let prevWithoutTrailingNewline = prev.slice(0, -1), lastBreak = prevWithoutTrailingNewline.lastIndexOf(`
22682
23561
  `);
22683
- if (prevWithoutTrailingNewline.slice(lastBreak + 1).trim().length > 0)
23562
+ previousLineNonBlank = prevWithoutTrailingNewline.slice(lastBreak + 1).trim().length > 0;
23563
+ }
23564
+ if (previousLineNonBlank)
23565
+ return null;
23566
+ }
23567
+ if (knownAppend !== void 0) {
23568
+ let lastSegment = this.ensureLastSegment(cache);
23569
+ if (lastSegment && this.segmentHasFence(cache, lastSegment)) {
23570
+ let scanStart = this.tokenMapsTrusted ? this.ensureSegmentSourceOffset(cache, lastSegment) : 0;
23571
+ if (this.endsInsideOpenFence(prev, scanStart))
23572
+ return null;
23573
+ }
23574
+ } else {
23575
+ let scanStart = this.tokenMapsTrusted ? this.ensureLastSegment(cache)?.srcOffset ?? 0 : 0;
23576
+ if ((this.tokenMapsTrusted || this.cacheHasFenceMarker(cache)) && this.endsInsideOpenFence(prev, scanStart))
22684
23577
  return null;
22685
23578
  }
22686
- let scanStart = this.tokenMapsTrusted ? this.ensureLastSegment(cache)?.srcOffset ?? 0 : 0;
22687
- return (this.tokenMapsTrusted || this.cacheHasFenceMarker(cache)) && this.endsInsideOpenFence(prev, scanStart) || this.mayContainReferenceDefinition(segment) ? null : segment;
23579
+ return this.mayContainReferenceDefinition(segment) ? null : segment;
22688
23580
  }
22689
- tryTailSegmentReparse(src, cached, env, md, segmentOverride) {
23581
+ tryTailSegmentReparse(src, cached, env, md, segmentOverride, knownAppend) {
22690
23582
  let lastSegment = segmentOverride ?? this.ensureLastSegment(cached);
22691
- if (!lastSegment || lastSegment.srcOffset <= 0 && lastSegment.tokenStart <= 0)
23583
+ if (!lastSegment)
22692
23584
  return null;
22693
- let stablePrefix = cached.src.slice(0, lastSegment.srcOffset);
22694
- if (!src.startsWith(stablePrefix))
23585
+ let directAppend = knownAppend !== void 0;
23586
+ if (directAppend && this.ensureSegmentSourceOffset(cached, lastSegment), lastSegment.srcOffset <= 0 && lastSegment.tokenStart <= 0)
22695
23587
  return null;
22696
- let prevTail = cached.src.slice(lastSegment.srcOffset), nextTail = src.slice(lastSegment.srcOffset);
23588
+ if (!directAppend) {
23589
+ let stablePrefix = cached.src.slice(0, lastSegment.srcOffset);
23590
+ if (!src.startsWith(stablePrefix))
23591
+ return null;
23592
+ }
23593
+ let prevTail = directAppend ? cached.lastSegmentSource ?? cached.src.slice(lastSegment.srcOffset) : cached.src.slice(lastSegment.srcOffset), nextTail = directAppend ? prevTail + knownAppend : src.slice(lastSegment.srcOffset);
22697
23594
  if (nextTail === prevTail)
22698
23595
  return null;
22699
- let appended = src.startsWith(cached.src) ? src.slice(cached.src.length) : null, postBlockSrc = this.getNormalizedUpdatedSource(cached, src);
23596
+ let appended = directAppend ? knownAppend : src.startsWith(cached.src) ? src.slice(cached.src.length) : null, postBlockSrc = directAppend && this.tokenMapsTrusted ? src : this.getNormalizedUpdatedSource(cached, src, knownAppend);
22700
23597
  if (appended) {
22701
23598
  let merged = this.tryContainerTailAppendMerge(src, cached, env, md, lastSegment, appended, postBlockSrc);
22702
23599
  if (merged)
22703
- return merged;
23600
+ return cached.lastSegmentSource = directAppend ? nextTail : void 0, merged;
22704
23601
  }
22705
23602
  if (this.mayContainReferenceDefinition(prevTail) || this.mayContainReferenceDefinition(nextTail))
22706
23603
  return null;
22707
23604
  try {
22708
23605
  let parsedTail = this.parseAtLineOffset(nextTail, env, md, lastSegment.lineStart, postBlockSrc), tailState = parsedTail.state, localLastSegment = this.getLastSegment(tailState.tokens, nextTail, 0, tailState.tokens.length, parsedTail.mapsShifted ? 0 : void 0, parsedTail.mapsShifted ? lastSegment.lineStart : void 0);
22709
- return lastSegment.lineStart > 0 && !parsedTail.mapsShifted && this.shiftTokenLines(tailState.tokens, lastSegment.lineStart), appended ? this.updateFenceMarkerCacheForAppend(cached, appended) : cached.hasFenceMarker = void 0, cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null, cached.globalStateCarry = void 0, cached.tokens.length = lastSegment.tokenStart, this.appendTokens(cached.tokens, tailState.tokens), cached.lineCount = lastSegment.lineStart + countLines(nextTail), localLastSegment ? cached.lastSegment = {
23606
+ return lastSegment.lineStart > 0 && !parsedTail.mapsShifted && this.shiftTokenLines(tailState.tokens, lastSegment.lineStart), appended ? directAppend ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended) : (cached.boundary = void 0, cached.hasFenceMarker = void 0), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null, (!directAppend || !appended) && (cached.globalStateCarry = void 0), cached.tokens.length = lastSegment.tokenStart, this.appendTokens(cached.tokens, tailState.tokens), cached.lineCount = lastSegment.lineStart + countLines(nextTail), localLastSegment ? (cached.lastSegment = {
22710
23607
  tokenStart: lastSegment.tokenStart + localLastSegment.tokenStart,
22711
23608
  tokenEnd: lastSegment.tokenStart + localLastSegment.tokenEnd,
22712
23609
  lineStart: parsedTail.mapsShifted ? localLastSegment.lineStart : lastSegment.lineStart + localLastSegment.lineStart,
22713
23610
  lineEnd: parsedTail.mapsShifted ? localLastSegment.lineEnd : lastSegment.lineStart + localLastSegment.lineEnd,
22714
23611
  srcOffset: lastSegment.srcOffset + localLastSegment.srcOffset
22715
- } : cached.lastSegment = null, cached.lastSegmentVerified = void 0, cached.tokens;
23612
+ }, cached.lastSegmentSource = directAppend ? nextTail.slice(localLastSegment.srcOffset) : void 0) : (cached.lastSegment = null, cached.lastSegmentSource = void 0), cached.lastSegmentVerified = void 0, cached.tokens;
22716
23613
  } catch {
22717
23614
  return null;
22718
23615
  }
22719
23616
  }
22720
23617
  tryUntrustedParagraphTailReparse(src, cached, env, md) {
22721
- if (this.endsWithBlankLine(cached.src))
23618
+ if (cached.boundary ? cached.boundary.endsWithBlankLine : this.endsWithBlankLine(cached.src))
22722
23619
  return null;
22723
23620
  let lastSegment = this.ensureLastSegment(cached);
22724
23621
  if (!lastSegment || cached.tokens[lastSegment.tokenStart]?.type !== "paragraph_open")
@@ -22749,6 +23646,7 @@ var StreamParser = class {
22749
23646
  return count;
22750
23647
  }
22751
23648
  hasVerifiedSegmentAnchor(cache, segment, md) {
23649
+ segment.srcOffset < 0 && this.ensureSegmentSourceOffset(cache, segment);
22752
23650
  let lineCount = cache.lineCount ?? countLines(cache.src), docLineCount = this.getDocLineCount(cache.src, lineCount);
22753
23651
  if (!(segment.lineStart >= 0 && segment.lineStart <= segment.lineEnd && segment.lineEnd <= docLineCount && segment.srcOffset < cache.src.length))
22754
23652
  return !1;
@@ -22775,6 +23673,10 @@ var StreamParser = class {
22775
23673
  return !1;
22776
23674
  }
22777
23675
  }
23676
+ normalizeSource(src) {
23677
+ return src.replace(/\r\n?/g, `
23678
+ `).replace(/\0/g, "\uFFFD");
23679
+ }
22778
23680
  cacheHasFenceMarker(cache) {
22779
23681
  return cache.hasFenceMarker === void 0 && (cache.hasFenceMarker = cache.src.includes("```") || cache.src.includes("~~~")), cache.hasFenceMarker;
22780
23682
  }
@@ -22784,16 +23686,12 @@ var StreamParser = class {
22784
23686
  let boundary = cache.src.slice(-2) + appended;
22785
23687
  cache.hasFenceMarker = boundary.includes("```") || boundary.includes("~~~");
22786
23688
  }
22787
- normalizeSource(src) {
22788
- return src.replace(/\r\n?/g, `
22789
- `).replace(/\0/g, "\uFFFD");
22790
- }
22791
- getNormalizedUpdatedSource(cache, next) {
23689
+ getNormalizedUpdatedSource(cache, next, knownAppend) {
22792
23690
  if (!this.normalizeLineEndings)
22793
23691
  return next;
22794
- if (!next.startsWith(cache.src))
23692
+ if (knownAppend === void 0 && !next.startsWith(cache.src))
22795
23693
  return this.normalizeSource(next);
22796
- let normalizedCached = cache.normalizedSrc ?? this.normalizeSource(cache.src), appended = next.slice(cache.src.length), normalizedAppend = this.normalizeSource(appended);
23694
+ let normalizedCached = cache.normalizedSrc ?? this.normalizeSource(cache.src), appended = knownAppend ?? next.slice(cache.src.length), normalizedAppend = this.normalizeSource(appended);
22797
23695
  return cache.src.endsWith("\r") && appended.startsWith(`
22798
23696
  `) && (normalizedAppend = normalizedAppend.slice(1)), normalizedCached + normalizedAppend;
22799
23697
  }
@@ -22880,15 +23778,26 @@ var StreamParser = class {
22880
23778
  peek() {
22881
23779
  return this.cache?.tokens ?? EMPTY_TOKENS;
22882
23780
  }
23781
+ hasCache() {
23782
+ return this.cache !== null;
23783
+ }
22883
23784
  getStats() {
22884
23785
  return { ...this.stats };
22885
23786
  }
23787
+ setCache(cache, md) {
23788
+ let snapshotState = this.cache?.snapshotState, nextCache = {
23789
+ ...cache,
23790
+ config: copyParserConfig(md),
23791
+ snapshotState
23792
+ };
23793
+ return snapshotState && (snapshotState.cache = nextCache), this.cache = nextCache, nextCache;
23794
+ }
22886
23795
  appendTokens(target, source, start = 0, end = source.length) {
22887
23796
  for (let i = start; i < end; i++)
22888
23797
  target.push(source[i]);
22889
23798
  }
22890
23799
  updateCacheLineCount(cache, lineCount) {
22891
- cache.lineCount = lineCount ?? countLines(cache.src), cache.lastSegment = void 0, cache.lastSegmentVerified = void 0, cache.normalizedSrc = void 0, cache.globalStateCarry = void 0;
23800
+ cache.lineCount = lineCount ?? countLines(cache.src), cache.lastSegment = void 0, cache.lastSegmentVerified = void 0, cache.normalizedSrc = void 0, cache.globalStateCarry = cache.src.slice(-GLOBAL_STATE_APPEND_SCAN_WINDOW), cache.boundary = void 0, cache.lastSegmentSource = void 0;
22892
23801
  }
22893
23802
  detectGlobalStateForAppend(cache, appended) {
22894
23803
  if (cache.globalStateReason)
@@ -22896,10 +23805,10 @@ var StreamParser = class {
22896
23805
  let text$1 = (cache.globalStateCarry ?? cache.src.slice(-GLOBAL_STATE_APPEND_SCAN_WINDOW)) + appended, reason = detectGlobalMarkdownState(text$1);
22897
23806
  return cache.globalStateCarry = text$1.length > GLOBAL_STATE_APPEND_SCAN_WINDOW ? text$1.slice(text$1.length - GLOBAL_STATE_APPEND_SCAN_WINDOW) : text$1, reason && (cache.globalStateReason = reason), reason;
22898
23807
  }
22899
- ensureLastSegment(cache) {
22900
- return cache.lastSegment !== void 0 || (cache.lastSegment = this.getLastSegment(cache.tokens, cache.src)), cache.lastSegment;
23808
+ ensureLastSegment(cache, skipSourceOffset = !1) {
23809
+ return cache.lastSegment !== void 0 || (cache.lastSegment = this.getLastSegment(cache.tokens, cache.src, 0, cache.tokens.length, void 0, void 0, skipSourceOffset)), cache.lastSegment;
22901
23810
  }
22902
- getLastSegment(tokens, src, tokenStart = 0, tokenEnd = tokens.length, knownSrcOffset, knownLineStart) {
23811
+ getLastSegment(tokens, src, tokenStart = 0, tokenEnd = tokens.length, knownSrcOffset, knownLineStart, skipSourceOffset = !1) {
22903
23812
  if (tokenEnd <= tokenStart)
22904
23813
  return null;
22905
23814
  let lineStart = Number.POSITIVE_INFINITY, lineEnd$2 = -1, depth = 0;
@@ -22917,7 +23826,7 @@ var StreamParser = class {
22917
23826
  tokenEnd,
22918
23827
  lineStart: resolvedStart,
22919
23828
  lineEnd: resolvedEnd,
22920
- srcOffset: this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
23829
+ srcOffset: skipSourceOffset ? -1 : this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
22921
23830
  };
22922
23831
  }
22923
23832
  continue;
@@ -22929,12 +23838,38 @@ var StreamParser = class {
22929
23838
  tokenEnd,
22930
23839
  lineStart: resolvedStart,
22931
23840
  lineEnd: resolvedEnd,
22932
- srcOffset: this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
23841
+ srcOffset: skipSourceOffset ? -1 : this.getLineStartOffset(src, resolvedStart, knownSrcOffset, knownLineStart)
22933
23842
  };
22934
23843
  }
22935
23844
  }
22936
23845
  return null;
22937
23846
  }
23847
+ segmentHasFence(cache, segment) {
23848
+ let end = Math.min(segment.tokenEnd, cache.tokens.length);
23849
+ for (let i = segment.tokenStart; i < end; i++)
23850
+ if (cache.tokens[i].type === "fence")
23851
+ return !0;
23852
+ return !1;
23853
+ }
23854
+ ensureSegmentSourceOffset(cache, segment) {
23855
+ if (segment.srcOffset < 0) {
23856
+ let lineCount = cache.lineCount;
23857
+ segment.srcOffset = lineCount !== void 0 && segment.lineStart <= lineCount && segment.lineEnd <= lineCount + 1 ? this.getLineStartOffsetFromEnd(cache.src, segment.lineStart, lineCount) : this.getLineStartOffset(cache.src, segment.lineStart);
23858
+ }
23859
+ return segment.srcOffset;
23860
+ }
23861
+ getLineStartOffsetFromEnd(src, line, lineCount) {
23862
+ if (line <= 0)
23863
+ return 0;
23864
+ let remaining = lineCount - line + 1, pos = src.length;
23865
+ for (; remaining > 0; ) {
23866
+ if (pos = src.lastIndexOf(`
23867
+ `, pos - 1), pos < 0)
23868
+ return 0;
23869
+ remaining--;
23870
+ }
23871
+ return pos + 1;
23872
+ }
22938
23873
  getLineStartOffset(src, line, knownSrcOffset, knownLineStart) {
22939
23874
  return knownSrcOffset !== void 0 && knownLineStart !== void 0 && line >= knownLineStart ? this.getLineStartOffsetFrom(src, knownSrcOffset, line - knownLineStart) : this.getLineStartOffsetFrom(src, 0, line);
22940
23875
  }
@@ -22961,7 +23896,7 @@ var StreamParser = class {
22961
23896
  return src.includes("]:") ? /(?:^|\n)[ \t]{0,3}\[[^\]\n]+\]:/.test(src) : !1;
22962
23897
  }
22963
23898
  canDirectlyParseAppend(cache) {
22964
- if (!this.tokenMapsTrusted || !this.endsWithBlankLine(cache.src))
23899
+ if (!this.tokenMapsTrusted || !(cache.boundary ? cache.boundary.endsWithBlankLine : this.endsWithBlankLine(cache.src)))
22965
23900
  return !1;
22966
23901
  let lastSegment = this.ensureLastSegment(cache);
22967
23902
  if (!lastSegment)
@@ -22994,8 +23929,9 @@ var StreamParser = class {
22994
23929
  }
22995
23930
  }
22996
23931
  tryListTailAppendMerge(src, cached, env, md, lastSegment, appended, listOpen, postBlockSrc) {
22997
- if (cached.src.length === 0 || cached.src.charCodeAt(cached.src.length - 1) !== 10)
23932
+ if (cached.src.length === 0 || !(cached.boundary ? cached.boundary.endsWithNewline : cached.src.charCodeAt(cached.src.length - 1) === 10))
22998
23933
  return null;
23934
+ this.ensureSegmentSourceOffset(cached, lastSegment);
22999
23935
  let segmentLineSpan = lastSegment.lineEnd - lastSegment.lineStart, segmentChars = cached.src.length - lastSegment.srcOffset;
23000
23936
  if (segmentLineSpan < this.MIN_LIST_LINES_FOR_MERGE && segmentChars < this.MIN_LIST_CHARS_FOR_MERGE)
23001
23937
  return null;
@@ -23013,10 +23949,10 @@ var StreamParser = class {
23013
23949
  return null;
23014
23950
  lineOffset > 0 && !mapsShifted && this.shiftTokenLines(inserted, lineOffset);
23015
23951
  let existingMode = this.getListParagraphMode(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level), appendedMode = this.getListParagraphMode(parsed, 0, parsed.length, 0);
23016
- (existingMode === "loose" || appendedMode === "loose" || this.endsWithBlankLine(cached.src) || (parsed[0]?.map?.[0] ?? 0) - (mapsShifted ? lineOffset : 0) > 0) && (this.setListParagraphVisibility(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level, !1), this.setListParagraphVisibility(inserted, 0, inserted.length, listOpen.level, !1)), cached.tokens.splice(cached.tokens.length - 1, 0, ...inserted), this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
23952
+ (existingMode === "loose" || appendedMode === "loose" || (cached.boundary ? cached.boundary.endsWithBlankLine : this.endsWithBlankLine(cached.src)) || (parsed[0]?.map?.[0] ?? 0) - (mapsShifted ? lineOffset : 0) > 0) && (this.setListParagraphVisibility(cached.tokens, lastSegment.tokenStart, cached.tokens.length, listOpen.level, !1), this.setListParagraphVisibility(inserted, 0, inserted.length, listOpen.level, !1)), cached.tokens.splice(cached.tokens.length - 1, 0, ...inserted), cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
23017
23953
  let nextLineCount = lineOffset + countLines(appended);
23018
23954
  cached.lineCount = nextLineCount;
23019
- let nextDocLineCount = this.getDocLineCount(src, nextLineCount);
23955
+ let nextDocLineCount = this.getCachedDocLineCount(cached, nextLineCount);
23020
23956
  return listOpen.map && (listOpen.map[1] = nextDocLineCount), cached.lastSegment = {
23021
23957
  tokenStart: lastSegment.tokenStart,
23022
23958
  tokenEnd: cached.tokens.length,
@@ -23026,8 +23962,9 @@ var StreamParser = class {
23026
23962
  }, cached.lastSegmentVerified = !0, cached.tokens;
23027
23963
  }
23028
23964
  tryTableTailAppendMerge(src, cached, env, md, lastSegment, appended, tableOpen, postBlockSrc) {
23029
- if (cached.src.length === 0 || cached.src.charCodeAt(cached.src.length - 1) !== 10 || /(?:^|\n)[ \t]*\n/.test(appended))
23965
+ if (cached.src.length === 0 || !(cached.boundary ? cached.boundary.endsWithNewline : cached.src.charCodeAt(cached.src.length - 1) === 10) || /(?:^|\n)[ \t]*\n/.test(appended))
23030
23966
  return null;
23967
+ this.ensureSegmentSourceOffset(cached, lastSegment);
23031
23968
  let segmentLineSpan = lastSegment.lineEnd - lastSegment.lineStart, segmentChars = cached.src.length - lastSegment.srcOffset;
23032
23969
  if (segmentLineSpan < this.MIN_TABLE_LINES_FOR_MERGE && segmentChars < this.MIN_TABLE_CHARS_FOR_MERGE)
23033
23970
  return null;
@@ -23051,10 +23988,10 @@ var StreamParser = class {
23051
23988
  return null;
23052
23989
  lineOffset !== 0 && !mapsShifted && this.shiftTokenLines(inserted, lineOffset);
23053
23990
  let insertAt = cachedSection.tbodyCloseIndex >= 0 ? cachedSection.tbodyCloseIndex : cachedSection.tableCloseIndex, previousLineCount = cached.lineCount ?? countLines(cached.src);
23054
- cached.tokens.splice(insertAt, 0, ...inserted), this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
23991
+ cached.tokens.splice(insertAt, 0, ...inserted), cached.boundary ? this.updateBoundaryStateForAppend(cached, appended) : this.updateFenceMarkerCacheForAppend(cached, appended), cached.src = src, cached.normalizedSrc = postBlockSrc, cached.env = env, cached.globalStateReason = null;
23055
23992
  let nextLineCount = previousLineCount + countLines(appended);
23056
23993
  cached.lineCount = nextLineCount;
23057
- let nextDocLineCount = this.getDocLineCount(src, nextLineCount);
23994
+ let nextDocLineCount = this.getCachedDocLineCount(cached, nextLineCount);
23058
23995
  if (tableOpen.map && (tableOpen.map[1] = nextDocLineCount), cachedSection.tbodyOpenIndex >= 0) {
23059
23996
  let tbodyOpen = cached.tokens[cachedSection.tbodyOpenIndex];
23060
23997
  tbodyOpen?.map && (tbodyOpen.map[1] = nextDocLineCount);
@@ -23161,7 +24098,7 @@ var StreamParser = class {
23161
24098
  case "paragraph_open":
23162
24099
  case "code_block":
23163
24100
  case "html_block":
23164
- return !this.endsWithBlankLine(cache.src);
24101
+ return !(cache.boundary ? cache.boundary.endsWithBlankLine : this.endsWithBlankLine(cache.src));
23165
24102
  default:
23166
24103
  return lastToken?.nesting === 1;
23167
24104
  }
@@ -23181,9 +24118,41 @@ var StreamParser = class {
23181
24118
  }
23182
24119
  return !0;
23183
24120
  }
24121
+ ensureBoundaryState(cache) {
24122
+ if (cache.boundary)
24123
+ return cache.boundary;
24124
+ let src = cache.src, len = src.length, endsWithNewline = len > 0 && src.charCodeAt(len - 1) === 10, lineEnd$2 = endsWithNewline ? len - 1 : len, lineStart = lineEnd$2 - 1;
24125
+ for (; lineStart >= 0 && src.charCodeAt(lineStart) !== 10; )
24126
+ lineStart--;
24127
+ let lineNonBlank = !1;
24128
+ for (let i = lineStart + 1; i < lineEnd$2; i++) {
24129
+ let ch = src.charCodeAt(i);
24130
+ if (ch !== 32 && ch !== 9) {
24131
+ lineNonBlank = !0;
24132
+ break;
24133
+ }
24134
+ }
24135
+ return cache.boundary = {
24136
+ currentLineNonBlank: endsWithNewline ? !1 : lineNonBlank,
24137
+ previousLineNonBlank: endsWithNewline ? lineNonBlank : !1,
24138
+ endsWithNewline,
24139
+ endsWithBlankLine: this.endsWithBlankLine(src)
24140
+ }, cache.boundary;
24141
+ }
24142
+ updateBoundaryStateForAppend(cache, appended) {
24143
+ let boundary = this.ensureBoundaryState(cache), currentLineNonBlank = boundary.currentLineNonBlank, previousLineNonBlank = boundary.previousLineNonBlank;
24144
+ for (let i = 0; i < appended.length; i++) {
24145
+ let ch = appended.charCodeAt(i);
24146
+ ch === 10 ? (previousLineNonBlank = currentLineNonBlank, currentLineNonBlank = !1) : ch !== 32 && ch !== 9 && (currentLineNonBlank = !0);
24147
+ }
24148
+ boundary.currentLineNonBlank = currentLineNonBlank, boundary.previousLineNonBlank = previousLineNonBlank, boundary.endsWithNewline = appended.length > 0 ? appended.charCodeAt(appended.length - 1) === 10 : boundary.endsWithNewline, boundary.endsWithBlankLine = cache.src.length + appended.length >= 2 && boundary.endsWithNewline && !previousLineNonBlank;
24149
+ }
23184
24150
  getDocLineCount(src, lineCount = countLines(src)) {
23185
24151
  return src.length === 0 ? 0 : src.charCodeAt(src.length - 1) === 10 ? lineCount : lineCount + 1;
23186
24152
  }
24153
+ getCachedDocLineCount(cache, lineCount) {
24154
+ return cache.src.length === 0 ? 0 : cache.boundary ? cache.boundary.endsWithNewline ? lineCount : lineCount + 1 : this.getDocLineCount(cache.src, lineCount);
24155
+ }
23187
24156
  shiftTokenLines(tokens, offset) {
23188
24157
  if (offset === 0)
23189
24158
  return;
@@ -23213,11 +24182,12 @@ function getParserRuleVersions(md) {
23213
24182
  core: md.core.ruler.version,
23214
24183
  block: md.block.ruler.version,
23215
24184
  inline: md.inline.ruler.version,
23216
- inline2: md.inline.ruler2.version
24185
+ inline2: md.inline.ruler2.version,
24186
+ inlineState: md.inline.State
23217
24187
  };
23218
24188
  }
23219
24189
  function hasParserRuleChanges(md, initial) {
23220
- return md.core.ruler.version !== initial.core || md.block.ruler.version !== initial.block || md.inline.ruler.version !== initial.inline || md.inline.ruler2.version !== initial.inline2;
24190
+ return md.core.ruler.version !== initial.core || md.block.ruler.version !== initial.block || md.inline.ruler.version !== initial.inline || md.inline.ruler2.version !== initial.inline2 || md.inline.State !== initial.inlineState;
23221
24191
  }
23222
24192
  function applyExperimentalOptions(options) {
23223
24193
  return options.experimental ? {
@@ -23570,9 +24540,25 @@ function markdownIt(presetName, options) {
23570
24540
  parse(src, env) {
23571
24541
  return md.stream.enabled ? getStreamParser().parse(src, env, md) : md.parse(src, env ?? {});
23572
24542
  },
24543
+ append(segment, env) {
24544
+ if (!md.stream.enabled)
24545
+ throw new Error("Stream append requires stream mode");
24546
+ return getStreamParser().append(segment, env, md);
24547
+ },
24548
+ snapshot() {
24549
+ return streamParser ? streamParser.snapshot() : null;
24550
+ },
24551
+ restore(snapshot) {
24552
+ if (!md.stream.enabled)
24553
+ throw new Error("Stream restore requires stream mode");
24554
+ return getStreamParser().restore(snapshot, md);
24555
+ },
23573
24556
  reset() {
23574
24557
  getStreamParser().reset();
23575
24558
  },
24559
+ hasCache() {
24560
+ return streamParser?.hasCache() ?? !1;
24561
+ },
23576
24562
  peek() {
23577
24563
  return streamParser ? streamParser.peek() : [];
23578
24564
  },
@@ -23890,7 +24876,7 @@ function container_plugin(md, name, options) {
23890
24876
  return tokens[idx].nesting === 1 && tokens[idx].attrJoin("class", name), slf.renderToken(tokens, idx, _options, env, slf);
23891
24877
  }
23892
24878
  options = options || {};
23893
- let min_markers = 3, marker_str = options.marker || ":", marker_char = marker_str.charCodeAt(0), marker_len = marker_str.length, validate = options.validate || validateDefault, render = options.render || renderDefault;
24879
+ let min_markers = 3, marker_str = options.marker || ":", marker_char = marker_str.charCodeAt(0), marker_len = marker_str.length, validate$1 = options.validate || validateDefault, render = options.render || renderDefault;
23894
24880
  function container(state, startLine, endLine, silent) {
23895
24881
  let pos, auto_closed = !1, start = state.bMarks[startLine] + state.tShift[startLine], max = state.eMarks[startLine];
23896
24882
  if (marker_char !== state.src.charCodeAt(start))
@@ -23902,7 +24888,7 @@ function container_plugin(md, name, options) {
23902
24888
  return !1;
23903
24889
  pos -= (pos - start) % marker_len;
23904
24890
  let markup = state.src.slice(start, pos), params = state.src.slice(pos, max);
23905
- if (!validate(params, markup))
24891
+ if (!validate$1(params, markup))
23906
24892
  return !1;
23907
24893
  if (silent)
23908
24894
  return !0;
@@ -24125,9 +25111,9 @@ function applyContainers(md) {
24125
25111
  function escapeTagForRegExp(tag) {
24126
25112
  return tag.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
24127
25113
  }
24128
- function findTagCloseIndexOutsideQuotes(input) {
25114
+ function findTagCloseIndexOutsideQuotes(input, start = 0) {
24129
25115
  let inSingle = !1, inDouble = !1;
24130
- for (let i = 0; i < input.length; i++) {
25116
+ for (let i = start; i < input.length; i++) {
24131
25117
  let ch = input[i];
24132
25118
  if (ch === "\\") {
24133
25119
  i++;
@@ -24998,7 +25984,7 @@ function createChildParseContext(parent, options = parent, overrides = {}) {
24998
25984
  ...overrides
24999
25985
  });
25000
25986
  }
25001
- var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE = /[_()[\]{}<>]/u, URL_PREFIX_HINT_RE = /^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i, URL_QUERY_OR_AUTH_HINT_RE = /[?#@]/u, PATH_SEPARATOR_RE = /[\\/]/u, DOMAINISH_TEXT_RE = /^[\p{L}\p{N}./\\-]+$/u, DOMAIN_LABEL_RE = /^[A-Za-z0-9-]{1,63}$/u, PUNYCODE_TLD_RE = /^xn--[a-z0-9-]{2,59}$/i, MARKET_TICKER_SYMBOL_RE = /^(?:[A-Z]{1,6}|\d{1,8})$/u, MARKET_TICKER_CONTEXT_SYMBOL_RE = /^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu, EXPLICIT_FILENAME_CONTEXT_RE = /文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu, FILENAME_CONTEXT_RE = /文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu, MARKET_TICKER_CONTEXT_RE = /股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu, LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT = 2e3, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH = 512, EMPTY_LINKIFY_DEMOTION_CONTEXT = {}, AMBIGUOUS_BARE_DOMAIN_EXTENSIONS = /* @__PURE__ */ new Set([
25987
+ var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE = /[_()[\]{}<>]/u, URL_PREFIX_HINT_RE = /^(?:https?:\/\/|ftp:\/\/|mailto:|www\.)/i, URL_QUERY_OR_AUTH_HINT_RE = /[?#@]/u, PATH_SEPARATOR_RE = /[\\/]/u, DOMAINISH_TEXT_RE = /^[\p{L}\p{N}./\\-]+$/u, DOMAIN_LABEL_RE = /^[A-Za-z0-9-]{1,63}$/u, PUNYCODE_TLD_RE = /^xn--[a-z0-9-]{2,59}$/i, MARKET_TICKER_SYMBOL_RE = /^(?:[A-Z]{1,6}|\d{1,8})$/u, MARKET_TICKER_CONTEXT_SYMBOL_RE = /^(?=.{1,12}$)[A-Z0-9]+(?:[-.][A-Z0-9]+)*$/iu, EXPLICIT_FILENAME_CONTEXT_RE = /文件名\s*[::]?|附件\s*[::]?|路径\s*[::]?|路徑\s*[::]?|文件列表\s*[::]?|文档列表\s*[::]?|文檔列表\s*[::]?|\bfile\s*names?\b\s*[::]?|\battachments?\b\s*[::]?|\bpaths?\b\s*[::]?|\bfile\s+lists?\b\s*[::]?|\bdocument\s+lists?\b\s*[::]?/iu, FILENAME_CONTEXT_RE = /文件名\s*[::]?|文件\s*[::]?|附件\s*[::]?|档案\s*[::]?|檔案\s*[::]?|文档\s*[::]?|文檔\s*[::]?|资料\s*[::]?|資料\s*[::]?|路径\s*[::]?|路徑\s*[::]?|\bfile\s*name\b\s*[::]?|\battachments?\b\s*[::]?|\bfiles?\b\s*[::]?|\bdocuments?\b\s*[::]?|\bdocs?\b\s*[::]?|\bpaths?\b\s*[::]?/iu, MARKET_TICKER_CONTEXT_RE = /股票代码|股票代碼|证券代码|證券代碼|(?:代码|代碼|交易所|后缀|後綴|市场|市場)(?=$|[\s::/|,,、()()])|\btickers?\b|\bsymbols?\b|\bexchanges?\b/iu, LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT = 2e3, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH = 16384, LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TOTAL_TEXT_LENGTH = 512 * LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT, EMPTY_LINKIFY_DEMOTION_CONTEXT = {}, AMBIGUOUS_BARE_DOMAIN_EXTENSIONS = /* @__PURE__ */ new Set([
25002
25988
  "ai",
25003
25989
  "md",
25004
25990
  "py",
@@ -25118,15 +26104,15 @@ var FILENAMEISH_EXTENSION_RE = /\.([a-z0-9]{1,15})$/i, FILENAMEISH_SEGMENT_RE =
25118
26104
  "yml",
25119
26105
  "zip",
25120
26106
  "zsh"
25121
- ]), linkifyDemotionContextCache = /* @__PURE__ */ new Map();
26107
+ ]), linkifyDemotionContextCache = /* @__PURE__ */ new Map(), linkifyDemotionContextCacheTextLength = 0;
25122
26108
  function rememberLinkifyDemotionContext(text$1, context) {
25123
26109
  if (!text$1 || text$1.length > LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TEXT_LENGTH)
25124
26110
  return context;
25125
- for (linkifyDemotionContextCache.set(text$1, context); linkifyDemotionContextCache.size > LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT; ) {
26111
+ for (linkifyDemotionContextCache.has(text$1) || (linkifyDemotionContextCacheTextLength += text$1.length), linkifyDemotionContextCache.set(text$1, context); linkifyDemotionContextCache.size > LINKIFY_DEMOTION_CONTEXT_CACHE_LIMIT || linkifyDemotionContextCacheTextLength > LINKIFY_DEMOTION_CONTEXT_CACHE_MAX_TOTAL_TEXT_LENGTH; ) {
25126
26112
  let oldestKey = linkifyDemotionContextCache.keys().next().value;
25127
26113
  if (!oldestKey)
25128
26114
  break;
25129
- linkifyDemotionContextCache.delete(oldestKey);
26115
+ linkifyDemotionContextCache.delete(oldestKey), linkifyDemotionContextCacheTextLength -= oldestKey.length;
25130
26116
  }
25131
26117
  return context;
25132
26118
  }
@@ -25174,7 +26160,7 @@ function inferContinuationLinkifyContext(raw, inherited) {
25174
26160
  })) && (continuation.filename = !0), inherited?.explicitFilename && continuation.filename && (continuation.explicitFilename = !0), inherited?.marketTicker && parts.every((part) => shouldDemoteFilenameLikeLinkify(part, { marketTicker: !0 })) && (continuation.marketTicker = !0), hasLinkifyDemotionContext(continuation) ? continuation : void 0;
25175
26161
  }
25176
26162
  function createLinkifyDemotionContextTracker(options, sticky = !1) {
25177
- let context;
26163
+ let context = ensureParseContext(options).linkifyDemotionSeedContext;
25178
26164
  return {
25179
26165
  options(raw) {
25180
26166
  return sticky || raw == null ? withLinkifyDemotionContext(options, context) : withLinkifyDemotionContext(options, mergeLinkifyDemotionContext(inferNextBlockLinkifyContext(raw), inferContinuationLinkifyContext(raw, context)));
@@ -25185,6 +26171,9 @@ function createLinkifyDemotionContextTracker(options, sticky = !1) {
25185
26171
  },
25186
26172
  reset() {
25187
26173
  context = void 0;
26174
+ },
26175
+ snapshot() {
26176
+ return context;
25188
26177
  }
25189
26178
  };
25190
26179
  }
@@ -25221,11 +26210,11 @@ function mayContainLinkifyDemotionContext(text$1) {
25221
26210
  }
25222
26211
  function inferLinkifyDemotionContext(contextText) {
25223
26212
  let text$1 = String(contextText ?? ""), cached = linkifyDemotionContextCache.get(text$1);
25224
- return cached ? (linkifyDemotionContextCache.delete(text$1), linkifyDemotionContextCache.set(text$1, cached), cached) : mayContainLinkifyDemotionContext(text$1) ? rememberLinkifyDemotionContext(text$1, {
26213
+ return cached || (mayContainLinkifyDemotionContext(text$1) ? rememberLinkifyDemotionContext(text$1, {
25225
26214
  explicitFilename: EXPLICIT_FILENAME_CONTEXT_RE.test(text$1),
25226
26215
  filename: FILENAME_CONTEXT_RE.test(text$1),
25227
26216
  marketTicker: MARKET_TICKER_CONTEXT_RE.test(text$1)
25228
- }) : rememberLinkifyDemotionContext(text$1, EMPTY_LINKIFY_DEMOTION_CONTEXT);
26217
+ }) : rememberLinkifyDemotionContext(text$1, EMPTY_LINKIFY_DEMOTION_CONTEXT));
25229
26218
  }
25230
26219
  function hasDomainAuthorityPrefix(text$1) {
25231
26220
  return isPlausibleBareDomain(text$1.split(/[\\/]/)[0] ?? "");
@@ -25264,6 +26253,21 @@ function setSyntheticLinkOrigin(token, origin) {
25264
26253
  function readSyntheticLinkOrigin(token) {
25265
26254
  return syntheticLinkOrigins.get(token);
25266
26255
  }
26256
+ function resolveLinkMarkup(token) {
26257
+ if (!token)
26258
+ return "";
26259
+ let origin = readSyntheticLinkOrigin(token);
26260
+ if (origin === "linkify" || origin === "autolink")
26261
+ return origin;
26262
+ let markup = typeof token.markup == "string" ? token.markup : "";
26263
+ return markup === "linkify" || markup === "autolink" ? markup : "";
26264
+ }
26265
+ function copySyntheticLinkOrigin(from, to) {
26266
+ if (!from || !to)
26267
+ return;
26268
+ let origin = readSyntheticLinkOrigin(from);
26269
+ origin && syntheticLinkOrigins.set(to, origin);
26270
+ }
25267
26271
  function registerCacheStableLinkValidator(validateLink$1) {
25268
26272
  cacheStableLinkValidators.add(validateLink$1);
25269
26273
  }
@@ -25501,7 +26505,7 @@ function fixLinkToken(tokens, raw) {
25501
26505
  } else if (curToken?.type === "text" && curToken.content?.endsWith("(") && tokens[i + 1]?.type === "link_open") {
25502
26506
  let match = curToken.content.match(/\[([^\]]+)\]/);
25503
26507
  if (match) {
25504
- let beforeText = curToken.content.slice(0, match.index), emphasisMatch = beforeText.match(/(\*+)$/), origin = getSyntheticLinkOrigin(tokens[i + 1]?.markup), replacerTokens = [];
26508
+ let beforeText = curToken.content.slice(0, match.index), emphasisMatch = beforeText.match(/(\*+)$/), linkOpenMarkup = tokens[i + 1]?.markup, origin = (linkOpenMarkup === "linkify" || linkOpenMarkup === "autolink") && (match.index ?? 0) + match[0].length === curToken.content.length - 1 ? "explicit" : getSyntheticLinkOrigin(linkOpenMarkup), replacerTokens = [];
25505
26509
  if (emphasisMatch) {
25506
26510
  beforeText = beforeText.slice(0, emphasisMatch.index), beforeText && replacerTokens.push(textToken(beforeText));
25507
26511
  let text$1 = match[1], type = emphasisMatch[1].length;
@@ -25730,7 +26734,7 @@ function fixStrongTokens(tokens) {
25730
26734
  for (; k < tokens.length && tokens[k].type === "text" && tokens[k].content === ""; )
25731
26735
  k++;
25732
26736
  let postToken = tokens[k];
25733
- markup === "__" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_") || postToken?.markup?.includes("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansStrong.add(strongIndex));
26737
+ markup === "__" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansStrong.add(strongIndex));
25734
26738
  } else if (type === "strong_close")
25735
26739
  cleansStrong.has(strongIndex) && t.markup === "__" && (t.type = "text", t.content = t.markup, t.raw = String(t.markup ?? ""), t.tag = "", t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null), strongIndex--, strongIndex < 0 && (strongIndex = 0);
25736
26740
  else if (type === "em_open") {
@@ -25742,7 +26746,7 @@ function fixStrongTokens(tokens) {
25742
26746
  for (; k < tokens.length && tokens[k].type === "text" && tokens[k].content === ""; )
25743
26747
  k++;
25744
26748
  let postToken = tokens[k];
25745
- markup === "_" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_") || postToken?.markup?.includes("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansEm.add(emIndex));
26749
+ markup === "_" && (preToken?.content?.endsWith("_") || postToken?.content?.startsWith("_")) && (t.type = "text", t.tag = "", t.content = markup, t.raw = markup, t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null, cleansEm.add(emIndex));
25746
26750
  } else
25747
26751
  type === "em_close" && (cleansEm.has(emIndex) && t.markup === "_" && (t.type = "text", t.content = t.markup, t.raw = String(t.markup ?? ""), t.tag = "", t.markup = "", t.attrs = null, t.map = null, t.info = "", t.meta = null), emIndex--, emIndex < 0 && (emIndex = 0));
25748
26752
  }
@@ -26051,36 +27055,35 @@ function hasTrailingPipeHeaderRowWithoutColon(line) {
26051
27055
  return cells !== null && cells.every((cell) => !cell.includes(":"));
26052
27056
  }
26053
27057
  function fixTableTokens(tokens, final = !1, source = "") {
26054
- let fixedTokens = [...tokens];
26055
27058
  if (tokens.length < 3)
26056
- return fixedTokens;
27059
+ return tokens;
26057
27060
  let i = tokens.length - 2, token = tokens[i];
26058
- if (token.type === "inline") {
26059
- let sourceMap = tokens[i - 1]?.map, tcontent = String(token.content ?? ""), headerContent = tcontent.split(`
27061
+ if (token.type !== "inline")
27062
+ return tokens;
27063
+ let sourceMap = tokens[i - 1]?.map, tcontent = String(token.content ?? ""), headerContent = tcontent.split(`
26060
27064
  `)[0] ?? "", [headerLine = "", separatorLine = "", ...rest] = tcontent.split(`
26061
27065
  `), hasTrailingNewlineSeparatorStart = !final && !tcontent.includes(`
26062
- `) && /\r?\n$/.test(source) && hasTrailingPipeHeaderRow(tcontent);
26063
- if (!final && (tcontent.includes(`
27066
+ `) && /\r?\n$/.test(source) && hasTrailingPipeHeaderRow(tcontent), fixedTokens = null;
27067
+ if (!final && (tcontent.includes(`
26064
27068
  `) && rest.length === 0 && hasTrailingPipeHeaderRow(headerLine) && isTableSeparatorRowWithPartialTail(separatorLine) || hasTrailingNewlineSeparatorStart)) {
26065
- let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
26066
- ...createStart(sourceMap),
26067
- ...body,
26068
- ...createEnd()
26069
- ];
26070
- fixedTokens.splice(i - 1, 3, ...insert);
26071
- } else if (tcontent.includes(`
27069
+ let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
27070
+ ...createStart(sourceMap),
27071
+ ...body,
27072
+ ...createEnd()
27073
+ ];
27074
+ fixedTokens = [...tokens], fixedTokens.splice(i - 1, 3, ...insert);
27075
+ } else if (tcontent.includes(`
26072
27076
  `) && rest.length === 0 && hasTrailingPipeHeaderRow(headerLine) && isTableSeparatorRow(separatorLine)) {
26073
- let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
26074
- ...createStart(sourceMap),
26075
- ...body,
26076
- ...createEnd()
26077
- ];
26078
- fixedTokens.splice(i - 1, 3, ...insert);
26079
- } else
26080
- tcontent.includes(`
26081
- `) && rest.length === 0 && hasTrailingPipeHeaderRowWithoutColon(headerLine) && isTruncatedSeparatorRow(separatorLine) && (token.content = tcontent.slice(0, -2), token.children.splice(2, 1));
26082
- }
26083
- return fixedTokens;
27077
+ let body = headerContent.slice(1, -1).split("|").map((i$1) => i$1.trim()).flatMap((i$1) => createTh(i$1)), insert = [
27078
+ ...createStart(sourceMap),
27079
+ ...body,
27080
+ ...createEnd()
27081
+ ];
27082
+ fixedTokens = [...tokens], fixedTokens.splice(i - 1, 3, ...insert);
27083
+ } else if (tcontent.includes(`
27084
+ `) && rest.length === 0 && hasTrailingPipeHeaderRowWithoutColon(headerLine) && isTruncatedSeparatorRow(separatorLine))
27085
+ return token.content = tcontent.slice(0, -2), token.children.splice(2, 1), tokens;
27086
+ return fixedTokens ?? tokens;
26084
27087
  }
26085
27088
  function findMatchingClose(src, startIdx, open, close) {
26086
27089
  let len = src.length;
@@ -26571,27 +27574,36 @@ function hashTolerantBoundaryContent(content) {
26571
27574
  hash = hash * 31 + content.charCodeAt(index) | 0;
26572
27575
  return hash.toString(36);
26573
27576
  }
26574
- function getTolerantBoundaryScanWindow(source) {
27577
+ function getTolerantBoundaryScanWindow(source, cache) {
26575
27578
  if (source.length <= TOLERANT_BOUNDARY_SCAN_TAIL_CHARS)
26576
27579
  return {
26577
27580
  source,
26578
27581
  lineOffset: 0
26579
27582
  };
27583
+ if (cache) {
27584
+ let cut = source.length - TOLERANT_BOUNDARY_SCAN_TAIL_CHARS, start$1 = source.indexOf(`
27585
+ `, cut);
27586
+ start$1 = start$1 === -1 ? source.length : start$1 + 1;
27587
+ let lineOffset$1 = cache.lineOffset + countLineBreaks(source.slice(cache.windowStart, start$1));
27588
+ return cache.lineOffset = lineOffset$1, cache.windowStart = start$1, {
27589
+ source: source.slice(start$1),
27590
+ lineOffset: lineOffset$1
27591
+ };
27592
+ }
26580
27593
  let start = source.length - TOLERANT_BOUNDARY_SCAN_TAIL_CHARS, nextLineBreak = source.indexOf(`
26581
27594
  `, start);
26582
- return nextLineBreak === -1 ? {
26583
- source: "",
26584
- lineOffset: countLineBreaks(source)
26585
- } : (start = nextLineBreak + 1, {
27595
+ start = nextLineBreak === -1 ? source.length : nextLineBreak + 1;
27596
+ let lineOffset = countLineBreaks(source.slice(0, start));
27597
+ return {
26586
27598
  source: source.slice(start),
26587
- lineOffset: countLineBreaks(source.slice(0, start))
26588
- });
27599
+ lineOffset
27600
+ };
26589
27601
  }
26590
- function mayContainTolerantMathBlockBoundaryOpener(markdown) {
27602
+ function mayContainTolerantMathBlockBoundaryOpener(markdown, scanWindowCache) {
26591
27603
  let fullSource = String(markdown ?? "");
26592
27604
  if (!fullSource || !fullSource.includes("$$") && !fullSource.includes("\\["))
26593
27605
  return !1;
26594
- let { source } = getTolerantBoundaryScanWindow(fullSource);
27606
+ let { source } = getTolerantBoundaryScanWindow(fullSource, scanWindowCache);
26595
27607
  if (!source)
26596
27608
  return !1;
26597
27609
  let lines = source.split(/\r?\n/), startLine = Math.max(0, lines.length - TOLERANT_BOUNDARY_SCAN_MAX_LINES - 2), delimiters = [["$$", "$$"], ["\\[", "\\]"]];
@@ -26605,11 +27617,11 @@ function mayContainTolerantMathBlockBoundaryOpener(markdown) {
26605
27617
  }
26606
27618
  return !1;
26607
27619
  }
26608
- function getTolerantMathBlockBoundaryStreamKey(markdown) {
27620
+ function getTolerantMathBlockBoundaryStreamKey(markdown, scanWindowCache) {
26609
27621
  let fullSource = String(markdown ?? "");
26610
27622
  if (!fullSource || !fullSource.includes("$$") && !fullSource.includes("\\["))
26611
27623
  return null;
26612
- let { source, lineOffset } = getTolerantBoundaryScanWindow(fullSource);
27624
+ let { source, lineOffset } = getTolerantBoundaryScanWindow(fullSource, scanWindowCache);
26613
27625
  if (!source)
26614
27626
  return null;
26615
27627
  let lines = source.split(/\r?\n/), startLine = Math.max(0, lines.length - TOLERANT_BOUNDARY_SCAN_MAX_LINES - 2), delimiters = [["$$", "$$"], ["\\[", "\\]"]];
@@ -27103,7 +28115,7 @@ function applyRenderRules(md) {
27103
28115
  return `<pre class="${info ? `language-${md.utils.escapeHtml(info.split(/\s+/g)[0])}` : ""}"><code>${md.utils.escapeHtml(String(tokenShape.content ?? ""))}</code></pre>`;
27104
28116
  });
27105
28117
  }
27106
- var HTML_LINK_OPEN_RE = /^<a[>\s]/i, HTML_LINK_CLOSE_RE = /^<\/a\s*>/i;
28118
+ var HTML_LINK_OPEN_RE = /^<a[>\s]/i, HTML_LINK_CLOSE_RE = /^<\/a\s*>/i, LINKIFY_SEED_RE = /[@:]|\/\/|\.\S/;
27107
28119
  function inlineTokenMayNeedLinkify(token, linkify$2) {
27108
28120
  if (token?.type !== "inline")
27109
28121
  return !1;
@@ -27129,13 +28141,33 @@ function inlineTokenMayNeedLinkify(token, linkify$2) {
27129
28141
  }
27130
28142
  function applyLinkifyCandidateFilter(md) {
27131
28143
  let ruler = md.core?.ruler, original = ruler.getNamedRules?.().find((rule) => rule.name === "linkify")?.fn;
27132
- typeof original == "function" && ruler.at("linkify", (state) => {
28144
+ if (typeof original != "function")
28145
+ return;
28146
+ let nativeLinkify = md.options.linkify ? md.linkify : void 0, nativeTest = nativeLinkify?.test, nativeMatch = nativeLinkify?.match, nativeBuilderPrototype = nativeLinkify?.re && Object.getPrototypeOf(nativeLinkify.re), screenedCache, seedSafe = !1;
28147
+ ruler.at("linkify", (state) => {
27133
28148
  if (!state.md?.options?.linkify)
27134
28149
  return;
27135
28150
  let tokens = Array.isArray(state.tokens) ? state.tokens : [], linkify$2 = state.md.linkify;
27136
- if (!linkify$2)
28151
+ if (!linkify$2 || !tokens.some((token) => token?.type === "inline"))
27137
28152
  return;
27138
- let candidates = tokens.filter((token) => inlineTokenMayNeedLinkify(token, linkify$2));
28153
+ let re = linkify$2.re, nativeBuilder = re && Object.getPrototypeOf(re) === nativeBuilderPrototype && !Object.values(re).some((value) => typeof value == "function"), nativeMethods = linkify$2.test === nativeTest && linkify$2.match === nativeMatch;
28154
+ if (nativeMethods && nativeBuilder && screenedCache !== re.cache) {
28155
+ screenedCache = re.cache;
28156
+ let { schema_names: schemas = [], tlds = [] } = re.opts;
28157
+ seedSafe = schemas.every((name) => name === "//" || name.endsWith(":")) && tlds.every((tld) => /^[\p{L}\p{N}-]+$/u.test(tld));
28158
+ }
28159
+ let canScreen = !!nativeMethods && !!nativeBuilder && seedSafe && (state.env?.__markstreamFinal !== !1 || !!re?.cache.link_fuzzy_search), candidates = tokens.filter((token) => {
28160
+ if (canScreen && token?.type === "inline") {
28161
+ let children = token.children;
28162
+ if (Array.isArray(children) && children.length > 0) {
28163
+ if (!children.some((child) => child?.type === "text" && LINKIFY_SEED_RE.test(String(child.content ?? ""))))
28164
+ return !1;
28165
+ } else if (!LINKIFY_SEED_RE.test(String(token.content ?? "")))
28166
+ return !1;
28167
+ canScreen = !1;
28168
+ }
28169
+ return inlineTokenMayNeedLinkify(token, linkify$2);
28170
+ });
27139
28171
  if (candidates.length)
27140
28172
  return original(Object.assign(Object.create(Object.getPrototypeOf(state)), state, { tokens: candidates }));
27141
28173
  });
@@ -27187,12 +28219,22 @@ function factory(opts = {}) {
27187
28219
  });
27188
28220
  registerCacheStableLinkValidator(validateLink$1), md.set({ validateLink: validateLink$1 });
27189
28221
  }
27190
- return applyInlineUrlValidation(md), applyLinkifyCandidateFilter(md), (opts.enableMath ?? !0) && applyMath(md, {
28222
+ return applyInlineUrlValidation(md), applyLinkifyCandidateFilter(md), (opts.cjkFriendly ?? !0) && md.use(markdownItCjkFriendlyPlugin), (opts.enableMath ?? !0) && applyMath(md, {
27191
28223
  ...getDefaultMathOptions() ?? {},
27192
28224
  ...opts.mathOptions ?? {}
27193
28225
  }), (opts.enableContainers ?? !0) && applyContainers(md), opts.enableFixIndentedCodeBlock !== !1 && applyFixIndentedCodeBlock(md), applyFixLinkTokens(md), applyFixStrongTokens(md), applyFixListItem(md), applyFixTableTokens(md), applyRenderRules(md), applyFixHtmlInlineTokens(md, { customHtmlTags: opts.customHtmlTags }), md;
27194
28226
  }
27195
- var NOT_WHITESPACE = /\S/;
28227
+ var regexCache = /* @__PURE__ */ new Map();
28228
+ function getCachedRegex(pattern, flags) {
28229
+ let key = flags ? `${pattern}:::${flags}` : pattern, regex = regexCache.get(key);
28230
+ if (!regex && (regex = new RegExp(pattern, flags), regexCache.set(key, regex), regexCache.size > 200)) {
28231
+ let keysToDelete = Array.from(regexCache.keys()).slice(0, 50);
28232
+ for (let keyToDelete of keysToDelete)
28233
+ regexCache.delete(keyToDelete);
28234
+ }
28235
+ return regex.lastIndex = 0, regex;
28236
+ }
28237
+ var NOT_WHITESPACE = /\S/, STARTS_LIKE_HTML_DOCUMENT_RE = /^(?:<!doctype\s+html[^>]*>\s*)?<html(?:\s[^>]*)?>/i, ENDS_WITH_HTML_CLOSE_RE = /<\/html>\s*$/i, NON_ELEMENT_MARKUP_START_RE = /^<\s*[!?]/, MARKUP_TAG_NAME_RE = /^([A-Z][\w:-]*)/i, SELF_CLOSING_END_RE$1 = /\/\s*>$/;
27196
28238
  function parseStandaloneHtmlDocument(markdown) {
27197
28239
  let firstNonWhitespace = markdown.search(NOT_WHITESPACE);
27198
28240
  if (firstNonWhitespace === -1 || markdown.charCodeAt(firstNonWhitespace) !== 60)
@@ -27200,7 +28242,7 @@ function parseStandaloneHtmlDocument(markdown) {
27200
28242
  let trimmed = markdown.trim();
27201
28243
  if (!trimmed)
27202
28244
  return null;
27203
- let startsLikeHtmlDocument = /^(?:<!doctype\s+html[^>]*>\s*)?<html(?:\s[^>]*)?>/i.test(trimmed), endsWithHtmlClose = /<\/html>\s*$/i.test(trimmed);
28245
+ let startsLikeHtmlDocument = STARTS_LIKE_HTML_DOCUMENT_RE.test(trimmed), endsWithHtmlClose = ENDS_WITH_HTML_CLOSE_RE.test(trimmed);
27204
28246
  return !startsLikeHtmlDocument || !endsWithHtmlClose ? null : [{
27205
28247
  type: "html_block",
27206
28248
  tag: "html",
@@ -27220,7 +28262,7 @@ function isCloseOnlyHtmlBlockForTag(node, tag) {
27220
28262
  if (node.type !== "html_block" || !tag)
27221
28263
  return !1;
27222
28264
  let raw = String(node.raw ?? node.content ?? "");
27223
- return new RegExp(String.raw`^\s*<\s*\/\s*${escapeTagForRegExp(tag)}\s*>\s*$`, "i").test(raw);
28265
+ return getCachedRegex(String.raw`^\s*<\s*\/\s*${escapeTagForRegExp(tag)}\s*>\s*$`, "i").test(raw);
27224
28266
  }
27225
28267
  var RAW_TEXT_HTML_TAGS = /* @__PURE__ */ new Set([
27226
28268
  "iframe",
@@ -27251,11 +28293,11 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
27251
28293
  tag: ""
27252
28294
  };
27253
28295
  }
27254
- let endRel = findTagCloseIndexOutsideQuotes(source.slice(start$1));
27255
- if (endRel === -1)
28296
+ let closeIndex = findTagCloseIndexOutsideQuotes(source, start$1);
28297
+ if (closeIndex === -1)
27256
28298
  return null;
27257
- let end = start$1 + endRel + 1, raw = source.slice(start$1, end);
27258
- if (/^<\s*[!?]/.test(raw))
28299
+ let end = closeIndex + 1, raw = source.slice(start$1, end);
28300
+ if (NON_ELEMENT_MARKUP_START_RE.test(raw))
27259
28301
  return {
27260
28302
  closing: !1,
27261
28303
  end,
@@ -27264,11 +28306,11 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
27264
28306
  };
27265
28307
  let body = raw.slice(1).trimStart(), closing = body.startsWith("/");
27266
28308
  closing && (body = body.slice(1).trimStart());
27267
- let tagMatch = body.match(/^([A-Z][\w:-]*)/i);
28309
+ let tagMatch = body.match(MARKUP_TAG_NAME_RE);
27268
28310
  return tagMatch?.[1] ? {
27269
28311
  closing,
27270
28312
  end,
27271
- selfClosing: /\/\s*>$/.test(raw),
28313
+ selfClosing: SELF_CLOSING_END_RE$1.test(raw),
27272
28314
  tag: tagMatch[1].toLowerCase()
27273
28315
  } : {
27274
28316
  closing: !1,
@@ -27277,7 +28319,7 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
27277
28319
  tag: ""
27278
28320
  };
27279
28321
  }, findRawTextClose = (rawTextTag, from) => {
27280
- let closeRe = new RegExp(String.raw`<\s*\/\s*${escapeTagForRegExp(rawTextTag)}(?=\s|>)`, "gi");
28322
+ let closeRe = getCachedRegex(String.raw`<\s*\/\s*${escapeTagForRegExp(rawTextTag)}(?=\s|>)`, "gi");
27281
28323
  closeRe.lastIndex = from;
27282
28324
  let match = closeRe.exec(source);
27283
28325
  if (!match || match.index == null)
@@ -27308,7 +28350,7 @@ function findNextHtmlBlockFromSource(source, tag, startIndex) {
27308
28350
  if (start === -1 || openEnd === -1)
27309
28351
  return null;
27310
28352
  let openTag = source.slice(start, openEnd + 1);
27311
- if (VOID_HTML_TAGS.has(lowerTag) || /\/\s*>$/.test(openTag))
28353
+ if (VOID_HTML_TAGS.has(lowerTag) || SELF_CLOSING_END_RE$1.test(openTag))
27312
28354
  return {
27313
28355
  raw: openTag,
27314
28356
  start,
@@ -27412,13 +28454,14 @@ function extendHtmlBlockCloseToLineEnding(source, startIndex) {
27412
28454
  ` ? end + 1 : startIndex;
27413
28455
  }
27414
28456
  function findLastClosingTagStart(raw, tag) {
27415
- let closeRe = new RegExp(String.raw`<\s*\/\s*${escapeTagForRegExp(tag)}(?=\s|>)`, "gi"), last = -1, match;
28457
+ let closeRe = getCachedRegex(String.raw`<\s*\/\s*${escapeTagForRegExp(tag)}(?=\s|>)`, "gi"), last = -1, match;
27416
28458
  for (; (match = closeRe.exec(raw)) !== null; )
27417
28459
  last = match.index;
27418
28460
  return last;
27419
28461
  }
28462
+ var NON_ELEMENT_HTML_BLOCK_START_RE = /^\s*(?:<!--|<!|<\?)/, FIRST_TAG_NAME_RE = /^\s*<([A-Z][\w:-]*)/i, SELF_CLOSING_END_RE = /\/\s*>$/, TRAILING_UNCLOSED_TAG_RE = /<[^>]*$/;
27420
28463
  function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
27421
- let lowerTag = tag.toLowerCase(), openTagRe = new RegExp(String.raw`^<\s*${lowerTag}(?=\s|>|/)`, "i"), closeTagRe = new RegExp(String.raw`^<\s*\/\s*${lowerTag}(?=\s|>)`, "i"), depth = 0, index = Math.max(0, startIndex);
28464
+ let lowerTag = tag.toLowerCase(), openTagRe = getCachedRegex(String.raw`^<\s*${lowerTag}(?=\s|>|/)`, "i"), closeTagRe = getCachedRegex(String.raw`^<\s*\/\s*${lowerTag}(?=\s|>)`, "i"), depth = 0, index = Math.max(0, startIndex);
27422
28465
  for (; index < rawHtml.length; ) {
27423
28466
  let lt = rawHtml.indexOf("<", index);
27424
28467
  if (lt === -1)
@@ -27438,7 +28481,7 @@ function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
27438
28481
  if (endRel === -1)
27439
28482
  return -1;
27440
28483
  let rawTag = slice.slice(0, endRel + 1);
27441
- /\/\s*>$/.test(rawTag) || depth++, index = lt + endRel + 1;
28484
+ SELF_CLOSING_END_RE.test(rawTag) || depth++, index = lt + endRel + 1;
27442
28485
  continue;
27443
28486
  }
27444
28487
  index = lt + 1;
@@ -27447,7 +28490,7 @@ function findMatchingCloseTagEnd(rawHtml, tag, startIndex) {
27447
28490
  }
27448
28491
  function parseHtmlBlock(token) {
27449
28492
  let raw = String(token.content ?? "");
27450
- if (/^\s*<!--/.test(raw) || /^\s*<!/.test(raw) || /^\s*<\?/.test(raw))
28493
+ if (NON_ELEMENT_HTML_BLOCK_START_RE.test(raw))
27451
28494
  return {
27452
28495
  type: "html_block",
27453
28496
  content: raw,
@@ -27455,7 +28498,7 @@ function parseHtmlBlock(token) {
27455
28498
  tag: "",
27456
28499
  loading: !1
27457
28500
  };
27458
- let tag = (raw.match(/^\s*<([A-Z][\w:-]*)/i)?.[1] || "").toLowerCase();
28501
+ let tag = (raw.match(FIRST_TAG_NAME_RE)?.[1] || "").toLowerCase();
27459
28502
  if (!tag)
27460
28503
  return {
27461
28504
  type: "html_block",
@@ -27464,10 +28507,10 @@ function parseHtmlBlock(token) {
27464
28507
  tag: "",
27465
28508
  loading: !1
27466
28509
  };
27467
- let openEnd = findTagCloseIndexOutsideQuotes(raw), openTag = openEnd === -1 ? raw : raw.slice(0, openEnd + 1), selfClosing = openEnd !== -1 && /\/\s*>$/.test(openTag), isVoid = VOID_HTML_TAGS.has(tag), attrs = parseTagAttrs(openTag), hasClosing = (openEnd === -1 ? -1 : findMatchingCloseTagEnd(raw, tag, openEnd + 1)) !== -1, loading = !(isVoid || selfClosing || hasClosing);
28510
+ let openEnd = findTagCloseIndexOutsideQuotes(raw), openTag = openEnd === -1 ? raw : raw.slice(0, openEnd + 1), selfClosing = openEnd !== -1 && SELF_CLOSING_END_RE.test(openTag), isVoid = VOID_HTML_TAGS.has(tag), attrs = parseTagAttrs(openTag), hasClosing = (openEnd === -1 ? -1 : findMatchingCloseTagEnd(raw, tag, openEnd + 1)) !== -1, loading = !(isVoid || selfClosing || hasClosing);
27468
28511
  return {
27469
28512
  type: "html_block",
27470
- content: loading ? `${raw.replace(/<[^>]*$/, "")}
28513
+ content: loading ? `${raw.replace(TRAILING_UNCLOSED_TAG_RE, "")}
27471
28514
  </${tag}>` : raw,
27472
28515
  raw,
27473
28516
  tag,
@@ -27537,7 +28580,7 @@ function applyNodeSourceMapRange(node, token, endLine, options) {
27537
28580
  }
27538
28581
  function cloneTokenWithMutableChildren(token) {
27539
28582
  let copy = Object.assign(Object.create(Object.getPrototypeOf(token)), token);
27540
- return Array.isArray(token.attrs) && (copy.attrs = token.attrs.map((attr) => [...attr])), Array.isArray(token.map) && (copy.map = [...token.map]), Array.isArray(token.children) && (copy.children = token.children.map((child) => cloneTokenWithMutableChildren(child))), copy;
28583
+ return Array.isArray(token.attrs) && (copy.attrs = token.attrs.map((attr) => [...attr])), Array.isArray(token.map) && (copy.map = [...token.map]), Array.isArray(token.children) && (copy.children = token.children.map((child) => cloneTokenWithMutableChildren(child))), copySyntheticLinkOrigin(token, copy), copy;
27541
28584
  }
27542
28585
  function isPlainObject(value) {
27543
28586
  if (!value || typeof value != "object")
@@ -27628,6 +28671,10 @@ function canCloneMarkdownTokenFast(token, enumerableKeys) {
27628
28671
  return !0;
27629
28672
  }
27630
28673
  function cloneMarkdownToken(token, cloneObjectFields = !0) {
28674
+ let cloned = cloneMarkdownTokenValue(token, cloneObjectFields);
28675
+ return copySyntheticLinkOrigin(token, cloned), cloned;
28676
+ }
28677
+ function cloneMarkdownTokenValue(token, cloneObjectFields = !0) {
27631
28678
  if (!cloneObjectFields)
27632
28679
  return cloneTokenWithMutableChildren(token);
27633
28680
  let allKeys = Reflect.ownKeys(token), enumerableKeys = Object.keys(token);
@@ -27821,12 +28868,16 @@ function createExplicitBracketMathContext() {
27821
28868
  function cloneExplicitBracketMathContext(context) {
27822
28869
  return { ...context };
27823
28870
  }
27824
- function setTolerantMathBoundaryStreamCache(runtime, source, key, explicitBracketMath = scanExplicitBracketMathStreamState(source).state) {
28871
+ function setTolerantMathBoundaryStreamCache(runtime, source, key, explicitBracketMath = scanExplicitBracketMathStreamState(source).state, scanWindow = {
28872
+ lineOffset: 0,
28873
+ windowStart: 0
28874
+ }) {
27825
28875
  runtime.tolerantMathBoundary = {
27826
28876
  explicitBracketMath,
27827
28877
  source,
27828
28878
  key,
27829
- pendingCandidate: key === null && mayContainTolerantMathBlockBoundaryOpener(source)
28879
+ pendingCandidate: key === null && mayContainTolerantMathBlockBoundaryOpener(source, scanWindow),
28880
+ scanWindow
27830
28881
  };
27831
28882
  }
27832
28883
  function sourceEndsWithSplitTolerantBoundaryPrefix(source) {
@@ -28075,7 +29126,7 @@ function stripPendingExplicitMathTail(markdown, runtime, useCache = !0) {
28075
29126
  let md = runtime.markdownIt;
28076
29127
  if (!hasMarkstreamMathPlugin(md))
28077
29128
  return markdown;
28078
- let previous = useCache ? runtime.pendingExplicitMathTail : void 0, state = previous?.source === markdown ? previous.state : previous && markdown.startsWith(previous.source) ? updateExplicitBracketMathStreamState(previous.state, markdown.slice(previous.source.length), previous.source.length - previous.state.lineBuffer.length).state : scanExplicitBracketMathStreamState(markdown).state;
29129
+ let previous = useCache ? runtime.pendingExplicitMathTail : void 0, state = previous?.source === markdown ? previous.state : previous && runtime.sourceExtends(previous.source, markdown) ? updateExplicitBracketMathStreamState(previous.state, markdown.slice(previous.source.length), previous.source.length - previous.state.lineBuffer.length).state : scanExplicitBracketMathStreamState(markdown).state;
28079
29130
  useCache && (runtime.pendingExplicitMathTail = {
28080
29131
  source: markdown,
28081
29132
  state
@@ -28135,13 +29186,16 @@ function syncTolerantMathBoundaryStreamCache(runtime, source) {
28135
29186
  let previous = runtime.tolerantMathBoundary;
28136
29187
  if (previous?.source === source)
28137
29188
  return;
28138
- let sourceExtendsPrevious = previous ? source.startsWith(previous.source) : !1, appended = sourceExtendsPrevious && previous ? source.slice(previous.source.length) : "", explicitBracketMathUpdate = sourceExtendsPrevious && previous ? updateExplicitBracketMathStreamState(previous.explicitBracketMath, appended, previous.source.length - previous.explicitBracketMath.lineBuffer.length) : scanExplicitBracketMathStreamState(source), nextExplicitBracketMath = explicitBracketMathUpdate.state, completesExplicitBracketMathClose = sourceExtendsPrevious && previous ? explicitBracketMathUpdate.closedOpenMath : !1;
29189
+ let sourceExtendsPrevious = previous ? runtime.sourceExtends(previous.source, source) : !1, appended = sourceExtendsPrevious && previous ? source.slice(previous.source.length) : "", explicitBracketMathUpdate = sourceExtendsPrevious && previous ? updateExplicitBracketMathStreamState(previous.explicitBracketMath, appended, previous.source.length - previous.explicitBracketMath.lineBuffer.length) : scanExplicitBracketMathStreamState(source), nextExplicitBracketMath = explicitBracketMathUpdate.state, completesExplicitBracketMathClose = sourceExtendsPrevious && previous ? explicitBracketMathUpdate.closedOpenMath : !1;
28139
29190
  if (previous && sourceExtendsPrevious && previous.key === null && previous.pendingCandidate === !1 && !completesExplicitBracketMathClose && !appendedChunkMayAffectTolerantMathBoundary(previous.source, appended) && !sourceEndsWithSplitTolerantBoundaryPrefix(source)) {
28140
29191
  previous.source = source, previous.explicitBracketMath = nextExplicitBracketMath;
28141
29192
  return;
28142
29193
  }
28143
- let nextKey = getTolerantMathBlockBoundaryStreamKey(source);
28144
- (previous && (previous && !sourceExtendsPrevious || previous.key !== nextKey || completesExplicitBracketMathClose) || !previous && nextKey) && runtime.resetStreamOnly(), setTolerantMathBoundaryStreamCache(runtime, source, nextKey, nextExplicitBracketMath);
29194
+ let scanWindow = sourceExtendsPrevious && previous ? previous.scanWindow : {
29195
+ lineOffset: 0,
29196
+ windowStart: 0
29197
+ }, nextKey = getTolerantMathBlockBoundaryStreamKey(source, scanWindow);
29198
+ (previous && (previous && !sourceExtendsPrevious || previous.key !== nextKey || completesExplicitBracketMathClose) || !previous && nextKey) && runtime.resetStreamOnly(), setTolerantMathBoundaryStreamCache(runtime, source, nextKey, nextExplicitBracketMath, scanWindow);
28145
29199
  }
28146
29200
  function shouldUseSyncParseForPendingTolerantMathBoundary(runtime) {
28147
29201
  let cache = runtime.tolerantMathBoundary;
@@ -28309,6 +29363,7 @@ var REUSABLE_INLINE_TOKEN_TYPES = /* @__PURE__ */ new Set([
28309
29363
  "code_block",
28310
29364
  "fence",
28311
29365
  "hr",
29366
+ "html_block",
28312
29367
  "inline",
28313
29368
  "math_block"
28314
29369
  ]);
@@ -28411,7 +29466,7 @@ function sameTokenAttrs(left, right) {
28411
29466
  function isSameTokenShapeForReuse(left, right) {
28412
29467
  return !!left && !!right && left.type === right.type && left.tag === right.tag && left.nesting === right.nesting && left.level === right.level && left.markup === right.markup && left.content === right.content && left.info === right.info && sameTokenMap(left, right) && sameTokenAttrs(left, right);
28413
29468
  }
28414
- function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, options, previousSeed) {
29469
+ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, options, linkifyDemotionContexts, linkifyDemotionContextOffset = 0, fallbackLinkifyDemotionContext) {
28415
29470
  let groupStarts = groups.starts;
28416
29471
  if (groupStarts.length === 0 || nodes.length !== groupStarts.length) {
28417
29472
  runtime.structuredStream = void 0;
@@ -28424,7 +29479,7 @@ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, opt
28424
29479
  lastToken: tokens[end - 1],
28425
29480
  tokenCount: end - start
28426
29481
  };
28427
- }), stableGroupCount = groups.mixed ? Math.max(0, groupStarts.length - 1) : sourceEndsWithBlankLine(source) ? groupStarts.length : Math.max(0, groupStarts.length - 1), seed = previousSeed && previousSeed.length >= stableGroupCount ? previousSeed.slice(0, stableGroupCount).concat(nodes.slice(stableGroupCount).map((node) => String(node.raw ?? ""))) : nodes.map((node) => String(node.raw ?? ""));
29482
+ }), stableGroupCount = groups.mixed ? Math.max(0, groupStarts.length - 1) : sourceEndsWithBlankLine(source) ? groupStarts.length : Math.max(0, groupStarts.length - 1), linkifyContextIndex = stableGroupCount - linkifyDemotionContextOffset - 1, linkifyDemotionContext = linkifyContextIndex >= 0 ? linkifyDemotionContexts?.[linkifyContextIndex] : fallbackLinkifyDemotionContext;
28428
29483
  runtime.structuredStream = {
28429
29484
  groupBoundaries,
28430
29485
  groupStarts,
@@ -28433,7 +29488,7 @@ function updateStructuredStreamCache(runtime, source, tokens, groups, nodes, opt
28433
29488
  mixed: groups.mixed,
28434
29489
  source,
28435
29490
  nodes,
28436
- seed,
29491
+ linkifyDemotionContext,
28437
29492
  stableGroupCount,
28438
29493
  requireClosingStrong: options.requireClosingStrong,
28439
29494
  validateLink: options.validateLink
@@ -28470,18 +29525,18 @@ function processTopLevelTokensWithReuse(runtime, source, tokens, options, callba
28470
29525
  if (!groups)
28471
29526
  return runtime.structuredStream = void 0, callbacks.processTokens(tokens, options);
28472
29527
  let groupStarts = groups.starts, stableGroupCount = previous && groups.mixed ? Math.min(previous.stableGroupCount, Math.max(0, previous.groupBoundaries.length - 1)) : previous?.stableGroupCount ?? 0;
28473
- if (previous && stableGroupCount > 0 && previous.requireClosingStrong === options.requireClosingStrong && previous.validateLink === options.validateLink && source.startsWith(previous.source) && groupStarts.length >= stableGroupCount && (mode === "append" || mode === "tail") && hasStableStructuredStreamGroupBoundaries(previous, tokens, groupStarts, stableGroupCount)) {
28474
- let tailStart = groupStarts[stableGroupCount] ?? tokens.length, tailNodes = callbacks.processTokens(tokens.slice(tailStart), {
29528
+ if (previous && stableGroupCount > 0 && previous.requireClosingStrong === options.requireClosingStrong && previous.validateLink === options.validateLink && runtime.sourceExtends(previous.source, source) && groupStarts.length >= stableGroupCount && (mode === "append" || mode === "tail") && hasStableStructuredStreamGroupBoundaries(previous, tokens, groupStarts, stableGroupCount)) {
29529
+ let tailStart = groupStarts[stableGroupCount] ?? tokens.length, tailOptions = {
28475
29530
  ...options,
28476
- linkifyDemotionSeed: previous.seed.slice(0, stableGroupCount)
28477
- }), expectedTailNodes = groupStarts.length - stableGroupCount;
29531
+ linkifyDemotionSeedContext: previous.linkifyDemotionContext
29532
+ }, tailNodes = callbacks.processTokens(tokens.slice(tailStart), tailOptions), expectedTailNodes = groupStarts.length - stableGroupCount;
28478
29533
  if (tailNodes.length === expectedTailNodes) {
28479
29534
  let result$1 = previous.nodes.slice(0, stableGroupCount).concat(tailNodes);
28480
- return runtime.structuredReuseTailStart = stableGroupCount, callbacks.recordReusedTopLevelNodes?.(stableGroupCount), updateStructuredStreamCache(runtime, source, tokens, groups, result$1, options, previous.seed), result$1;
29535
+ return runtime.structuredReuseTailStart = stableGroupCount, callbacks.recordReusedTopLevelNodes?.(stableGroupCount), updateStructuredStreamCache(runtime, source, tokens, groups, result$1, options, tailOptions.linkifyDemotionResultContexts, stableGroupCount, previous.linkifyDemotionContext), result$1;
28481
29536
  }
28482
29537
  }
28483
29538
  let result = callbacks.processTokens(tokens, options);
28484
- return updateStructuredStreamCache(runtime, source, tokens, groups, result, options), result;
29539
+ return updateStructuredStreamCache(runtime, source, tokens, groups, result, options, options.linkifyDemotionResultContexts), result;
28485
29540
  }
28486
29541
  function isDetailsOpenHtmlBlock(node) {
28487
29542
  if (node.type !== "html_block" || String(node.tag ?? "").toLowerCase() !== "details")
@@ -28566,7 +29621,7 @@ function parseSiblingHtmlBlockChildren(blocks, context, options, final, useCache
28566
29621
  validateLink: options.validateLink
28567
29622
  }), children.flat();
28568
29623
  }
28569
- function structureGenericHtmlBlockChildren(nodes, context, options, final, tailStart = 0) {
29624
+ function structureGenericHtmlBlockChildren(nodes, context, options, final) {
28570
29625
  let processNode = (node) => {
28571
29626
  if (node?.type !== "html_block")
28572
29627
  return node;
@@ -28583,12 +29638,9 @@ function structureGenericHtmlBlockChildren(nodes, context, options, final, tailS
28583
29638
  if (!innerRaw.trim() || !hasStructuredHtmlWrapperMarkers(innerRaw))
28584
29639
  return node;
28585
29640
  let childOptions = buildDetailsChildParseOptions(options, final), siblingHtmlBlocks = hasClose ? null : splitSiblingHtmlBlockFragments(innerRaw), useSiblingCache = !options.isFragment && typeof options.preTransformTokens != "function" && typeof options.postTransformTokens != "function" && typeof options.postTransformNodes != "function" && context.markdownIt.__markstreamHasCustomParserExtensions === !1 && isCacheStableLinkValidator(options.validateLink), children = siblingHtmlBlocks ? parseSiblingHtmlBlockChildren(siblingHtmlBlocks, context, childOptions, final, useSiblingCache) : parseDetailsFragmentChildren(innerRaw, context, childOptions);
28586
- return shouldStructureGenericHtmlBlockChildren(children) ? {
28587
- ...node,
28588
- children
28589
- } : node;
29641
+ return shouldStructureGenericHtmlBlockChildren(children) && (fields.children = children), node;
28590
29642
  };
28591
- return tailStart <= 0 ? nodes.map(processNode) : nodes.slice(0, tailStart).concat(nodes.slice(tailStart).map(processNode));
29643
+ return nodes.map(processNode);
28592
29644
  }
28593
29645
  function hasTopLevelHtmlBlock(nodes, start = 0) {
28594
29646
  for (let i = start; i < nodes.length; i++)
@@ -28699,12 +29751,18 @@ function combineStructuredDetailsHtmlBlocks(nodes, source, context, options, fin
28699
29751
  }
28700
29752
  return [merged, cursor];
28701
29753
  }
28702
- function mergeSplitTopLevelHtmlBlocks(nodes, final, source, context, options) {
29754
+ function findNodeRawPosition(node, nodeRaw, source, cursor, context) {
29755
+ if (!nodeRaw)
29756
+ return -1;
29757
+ let anchor = context.getInternalNodeSourceRange(node)?.start ?? -1, anchored = anchor >= cursor && source.startsWith(nodeRaw, anchor);
29758
+ return node?.type === "html_block" ? anchored && anchor === cursor ? anchor : source.indexOf(nodeRaw, cursor) : anchor < 0 ? source.indexOf(nodeRaw, cursor) : anchored ? anchor : -1;
29759
+ }
29760
+ function mergeSplitTopLevelHtmlBlocks(nodes, final, source, context, options, initialSourceCursor = 0) {
28703
29761
  if (!source)
28704
29762
  return nodes;
28705
- let merged = nodes.slice(), sourceHtmlCursor = 0;
29763
+ let merged = nodes.slice(), sourceHtmlCursor = initialSourceCursor;
28706
29764
  for (let i = 0; i < merged.length; i++) {
28707
- let node = merged[i], nodeRaw = getMergeableNodeRaw(node), nodePos = nodeRaw ? source.indexOf(nodeRaw, sourceHtmlCursor) : -1;
29765
+ let node = merged[i], nodeRaw = getMergeableNodeRaw(node), nodePos = findNodeRawPosition(node, nodeRaw, source, sourceHtmlCursor, context);
28708
29766
  if (node?.type !== "html_block") {
28709
29767
  nodePos !== -1 && (sourceHtmlCursor = nodePos + nodeRaw.length);
28710
29768
  continue;
@@ -28812,7 +29870,7 @@ function parseEmphasisToken(tokens, startIndex, parseInlineTokens$1, options) {
28812
29870
  };
28813
29871
  }
28814
29872
  function TRAILING_OWN_FENCE_CANDIDATE_LINE_RE(marker) {
28815
- return /* @__PURE__ */ new RegExp(`(?:^|\\r\\n|\\n|\\r) {0,3}${marker}+[ \\t]*$`);
29873
+ return getCachedRegex(`(?:^|\\r\\n|\\n|\\r) {0,3}${marker}+[ \\t]*$`);
28816
29874
  }
28817
29875
  var DIFF_HEADER_PREFIXES = [
28818
29876
  "diff ",
@@ -29094,7 +30152,8 @@ function parseHtmlInlineCodeToken(token, tokens, i, parseInlineTokens$1, raw, pP
29094
30152
  attrs: normalizedAttrs,
29095
30153
  children: normalizedChildren$1,
29096
30154
  loading: !fragment$1.closed,
29097
- raw: fragment$1.html || code$1
30155
+ raw: fragment$1.html || code$1,
30156
+ markup: "html"
29098
30157
  }, fragment$1.nextIndex];
29099
30158
  }
29100
30159
  if (selfClosing)
@@ -29245,7 +30304,8 @@ function parseLinkToken(tokens, startIndex, parseInlineTokens$1, options) {
29245
30304
  children,
29246
30305
  raw: `[${linkText}](${href}${title ? ` "${title}"` : ""})`,
29247
30306
  loading,
29248
- attrs: normalizedAttrs
30307
+ attrs: normalizedAttrs,
30308
+ markup: resolveLinkMarkup(openToken)
29249
30309
  },
29250
30310
  nextIndex: i < tokens.length ? i + 1 : tokens.length
29251
30311
  };
@@ -29475,7 +30535,8 @@ function recoverMarkdownLinkFromTrailingText(state, token) {
29475
30535
  content: label,
29476
30536
  raw: label
29477
30537
  }],
29478
- raw: `[${label}](${href}${linkToken.title ? ` "${linkToken.title}"` : ""})`
30538
+ raw: `[${label}](${href}${linkToken.title ? ` "${linkToken.title}"` : ""})`,
30539
+ markup: resolveLinkMarkup(token)
29479
30540
  }), !0;
29480
30541
  }
29481
30542
  function recoverMarkdownImageFromLoadingImageTail(state, token) {
@@ -29538,7 +30599,8 @@ function buildLoadingOuterImageLinkNode(imageNode, href = "", title = null) {
29538
30599
  text: text$1,
29539
30600
  children: [imageNode],
29540
30601
  raw: `[${text$1}](${href}${title ? ` "${title}"` : ""})`,
29541
- loading: !0
30602
+ loading: !0,
30603
+ markup: ""
29542
30604
  };
29543
30605
  }
29544
30606
  function buildLoadingImageNodeFromRaw(raw) {
@@ -29662,7 +30724,8 @@ function handleInlineLinkContent(state, content, _token) {
29662
30724
  content: text$1,
29663
30725
  raw: text$1
29664
30726
  }],
29665
- loading: loading$1
30727
+ loading: loading$1,
30728
+ markup: ""
29666
30729
  }), state.index += index, !0;
29667
30730
  }
29668
30731
  let linkContentEnd = content.indexOf(")", linkEnd), href = linkContentEnd !== -1 ? content.slice(linkEnd + 2, linkContentEnd) : "", loading = linkContentEnd === -1, emphasisMatch = textNodeContent.match(/\*+$/);
@@ -29696,7 +30759,8 @@ function handleInlineLinkContent(state, content, _token) {
29696
30759
  content: text$1,
29697
30760
  raw: text$1
29698
30761
  }],
29699
- loading
30762
+ loading,
30763
+ markup: ""
29700
30764
  }), type === 1) {
29701
30765
  newTokens.push({
29702
30766
  type: "em_close",
@@ -29740,7 +30804,8 @@ function handleInlineLinkContent(state, content, _token) {
29740
30804
  content: text$1,
29741
30805
  raw: text$1
29742
30806
  }],
29743
- loading
30807
+ loading,
30808
+ markup: ""
29744
30809
  });
29745
30810
  let afterText = linkContentEnd !== -1 ? content.slice(linkContentEnd + 1) : "";
29746
30811
  return afterText && (state.dispatchToken({
@@ -30351,7 +31416,7 @@ function handleTextToken(state, token) {
30351
31416
  }
30352
31417
  trailingTextStart < state.result.length && (content.startsWith(trailingTextContent) ? (state.currentTextNode = null, state.result.length = trailingTextStart) : state.currentTextNode = state.result[state.result.length - 1]);
30353
31418
  let nextToken = state.tokens[state.index + 1];
30354
- if ((content === "`" || content === "|" || content === "$") && !hasEscapedMarkup(token, `\\${content}`) || /^\*+$/.test(content) && !hasEscapedMarkup(token, "\\*")) {
31419
+ if (state.options?.final !== !0 && ((content === "`" || content === "|" || content === "$") && !hasEscapedMarkup(token, `\\${content}`) || /^\*+$/.test(content) && !hasEscapedMarkup(token, "\\*"))) {
30355
31420
  state.index++;
30356
31421
  return;
30357
31422
  }
@@ -30551,9 +31616,20 @@ function dispatchInlineToken(state, token) {
30551
31616
  function handleReference(state, token) {
30552
31617
  state.resetCurrentTextNode(), state.pushParsed(parseReferenceToken(token)), state.index++;
30553
31618
  }
31619
+ var TEXT_RECOVERY_MARKER_RE = /[!$(*[\\\]_`|~]/;
30554
31620
  function parseInlineTokens(tokens, raw, pPreToken, options) {
30555
31621
  if (!tokens || tokens.length === 0)
30556
31622
  return [];
31623
+ if (tokens.length === 1 && tokens[0].type === "text") {
31624
+ let content = tokens[0].content;
31625
+ if (typeof content == "string" && content && content !== "<" && !content.endsWith("undefined") && !TEXT_RECOVERY_MARKER_RE.test(content))
31626
+ return [{
31627
+ type: "text",
31628
+ content,
31629
+ raw: content,
31630
+ center: !1
31631
+ }];
31632
+ }
30557
31633
  let parseContext = ensureParseContext(options), inheritedContext = parseContext.linkifyDemotionContext, inferredContext = inferLinkifyDemotionContext(raw), linkifyDemotionContext = {
30558
31634
  filename: inheritedContext?.filename || inferredContext.filename,
30559
31635
  explicitFilename: inheritedContext?.explicitFilename || inferredContext.explicitFilename,
@@ -30592,7 +31668,7 @@ function parseInlineTokens(tokens, raw, pPreToken, options) {
30592
31668
  function pushToken(token) {
30593
31669
  resetCurrentTextNode();
30594
31670
  let node = cloneTokenWithMutableChildren(token);
30595
- state.result.push(node);
31671
+ node.type === "link" && (node.markup = resolveLinkMarkup(token)), state.result.push(node);
30596
31672
  }
30597
31673
  function pushText(content, raw$1) {
30598
31674
  state.currentTextNode ? (state.currentTextNode.content += content, state.currentTextNode.raw += raw$1 ?? content) : (state.currentTextNode = {
@@ -31341,7 +32417,7 @@ function parseBasicBlockToken(tokens, index, options, parseInlineTokens$1) {
31341
32417
  return includeSourceMap && applyNodeSourceMap(paragraphNode, token, options), [paragraphNode, index + 1];
31342
32418
  }
31343
32419
  if (htmlBlockNode.tag && tagSets?.customTagSet?.has(htmlBlockNode.tag)) {
31344
- let tag = htmlBlockNode.tag, context = isParseContext(options) ? options : void 0, source = String(context?.sourceMarkdown ?? ""), cursor = Number(context?.customHtmlBlockCursor ?? 0), mappedLineStart = Array.isArray(token.map) ? lineToIndex(source, Number(token.map?.[0] ?? 0)) : 0, fromSource = findNextCustomHtmlBlockFromSource(source, tag, Math.max(clampNonNegative(cursor), clampNonNegative(mappedLineStart)));
32420
+ let tag = htmlBlockNode.tag, context = isParseContext(options) ? options : void 0, source = String(context?.sourceMarkdown ?? ""), cursor = Number(context?.customHtmlBlockCursor ?? 0), mappedLine = Number(token.map?.[0] ?? 0), mappedLineStart = Array.isArray(token.map) ? context?.sourceLineOffsets?.[mappedLine] ?? lineToIndex(source, mappedLine) : 0, fromSource = findNextCustomHtmlBlockFromSource(source, tag, Math.max(clampNonNegative(cursor), clampNonNegative(mappedLineStart)));
31345
32421
  fromSource && context && (context.customHtmlBlockCursor = fromSource.end);
31346
32422
  let rawHtml = String(fromSource?.raw ?? htmlBlockNode.raw ?? ""), openEnd = findTagCloseIndexOutsideQuotes(rawHtml), openTag = openEnd !== -1 ? rawHtml.slice(0, openEnd + 1) : rawHtml, selfClosing = openEnd !== -1 && /\/\s*>\s*$/.test(openTag), closeRange = openEnd === -1 ? null : findMatchingCloseTagRange(rawHtml, tag, openEnd + 1), closeIndex = closeRange?.start ?? -1, inner = "";
31347
32423
  openEnd !== -1 && (closeIndex !== -1 && openEnd < closeIndex ? inner = rawHtml.slice(openEnd + 1, closeIndex) : inner = rawHtml.slice(openEnd + 1)), closeIndex === -1 && (inner = stripTrailingPartialClosingTag(inner, tag));
@@ -31521,15 +32597,11 @@ function maybePromoteCustomNodeFromParagraph(node, options) {
31521
32597
  function processTokensWithContext(tokens, options, parseInlineTokens$1) {
31522
32598
  if (!tokens || !Array.isArray(tokens))
31523
32599
  return [];
31524
- let result = [], linkifyContext = createLinkifyDemotionContextTracker(options), seedRaws = options.linkifyDemotionSeed;
31525
- if (Array.isArray(seedRaws) && seedRaws.length)
31526
- for (let raw of seedRaws)
31527
- linkifyContext.remember(String(raw ?? ""));
31528
- let includeSourceMap = options?.includeSourceMap === !0, i = 0;
32600
+ let result = [], resultContexts = [], linkifyContext = createLinkifyDemotionContextTracker(options), includeSourceMap = options?.includeSourceMap === !0, i = 0;
31529
32601
  for (; i < tokens.length; ) {
31530
32602
  let handled = parseCommonBlockToken(tokens, i, linkifyContext.options(), containerTokenHandlers, parseInlineTokens$1);
31531
32603
  if (handled) {
31532
- recordInternalNodeSourceRange(handled[0], tokens[i], options), result.push(handled[0]), linkifyContext.remember(handled[0].raw), i = handled[1];
32604
+ recordInternalNodeSourceRange(handled[0], tokens[i], options), result.push(handled[0]), linkifyContext.remember(handled[0].raw), resultContexts.push(linkifyContext.snapshot()), i = handled[1];
31533
32605
  continue;
31534
32606
  }
31535
32607
  let token = tokens[i];
@@ -31619,42 +32691,52 @@ function processTokensWithContext(tokens, options, parseInlineTokens$1) {
31619
32691
  i += 1;
31620
32692
  break;
31621
32693
  }
32694
+ let context = linkifyContext.snapshot();
32695
+ for (; resultContexts.length < result.length; )
32696
+ resultContexts.push(context);
31622
32697
  }
31623
- return result;
32698
+ return options.linkifyDemotionResultContexts = resultContexts, result;
31624
32699
  }
31625
32700
  function getCachedSourceLineOffsets(runtime, source) {
31626
32701
  let cached = runtime.sourceLineOffsets;
31627
- if (cached && cached.source === source)
32702
+ if (cached?.source === source)
31628
32703
  return cached.offsets;
31629
- if (cached && source.length > cached.source.length && source.startsWith(cached.source)) {
32704
+ if (cached && source.length > cached.source.length && runtime.sourceExtends(cached.source, source)) {
31630
32705
  let offsets$1 = cached.offsets;
31631
32706
  for (let i = cached.source.length; i < source.length; i++)
31632
32707
  source.charCodeAt(i) === 10 && offsets$1.push(i + 1);
31633
32708
  return cached.source = source, offsets$1;
31634
32709
  }
31635
- let offsets = [0];
31636
- for (let i = 0; i < source.length; i++)
31637
- source.charCodeAt(i) === 10 && offsets.push(i + 1);
32710
+ let offsets = computeSourceLineOffsets(source);
31638
32711
  return runtime.sourceLineOffsets = {
31639
32712
  source,
31640
32713
  offsets
31641
32714
  }, offsets;
31642
32715
  }
32716
+ function computeSourceLineOffsets(source) {
32717
+ let offsets = [0];
32718
+ for (let i = 0; i < source.length; i++)
32719
+ source.charCodeAt(i) === 10 && offsets.push(i + 1);
32720
+ return offsets;
32721
+ }
31643
32722
  var parserRuntimes = /* @__PURE__ */ new WeakMap(), wrappedMarkdownItInstances = /* @__PURE__ */ new WeakSet(), wrappedStreamInstances = /* @__PURE__ */ new WeakSet();
31644
32723
  function sameSemantics(left, right) {
31645
32724
  return left.customHtmlTags === right.customHtmlTags && left.hasCustomParserExtensions === right.hasCustomParserExtensions && left.includeSourceMap === right.includeSourceMap && left.postTransformNodes === right.postTransformNodes && left.postTransformTokens === right.postTransformTokens && left.preTransformTokens === right.preTransformTokens && left.requireClosingStrong === right.requireClosingStrong && left.reuseStableTopLevelNodes === right.reuseStableTopLevelNodes && left.streamParse === right.streamParse && left.validateLink === right.validateLink;
31646
32725
  }
31647
32726
  var ParserRuntime = class {
31648
32727
  constructor(markdownIt$1) {
31649
- this.streamParseEnvs = /* @__PURE__ */ new Map(), this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.finalized = !1, this.resettingStream = !1, this.streamStateActive = !1, this.streamResetInCurrentRootParse = !1, this.markdownIt = markdownIt$1;
32728
+ this.streamParseEnvs = /* @__PURE__ */ new Map(), this.htmlPassIdentityPreserving = !1, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.finalized = !1, this.resettingStream = !1, this.streamStateActive = !1, this.streamResetInCurrentRootParse = !1, this.markdownIt = markdownIt$1;
32729
+ }
32730
+ sourceExtends(previousSource, currentSource) {
32731
+ return this.sourceRelationPrevious === previousSource && this.sourceRelationCurrent === currentSource ? !0 : currentSource.startsWith(previousSource) ? (this.sourceRelationPrevious = previousSource, this.sourceRelationCurrent = currentSource, !0) : !1;
31650
32732
  }
31651
32733
  beginRootParse(source, semantics) {
31652
32734
  this.streamResetInCurrentRootParse = !1;
31653
- let sourceChangedNonAppend = this.documentSource !== void 0 && source !== this.documentSource && !source.startsWith(this.documentSource), semanticsChanged = this.semantics !== void 0 && !sameSemantics(this.semantics, semantics);
32735
+ let sourceChangedNonAppend = this.documentSource !== void 0 && source !== this.documentSource && !this.sourceExtends(this.documentSource, source), semanticsChanged = this.semantics !== void 0 && !sameSemantics(this.semantics, semantics);
31654
32736
  (this.finalized || sourceChangedNonAppend || semanticsChanged) && this.resetDocument(this.streamStateActive), this.finalized = !1, this.documentSource = source, this.semantics = semantics;
31655
32737
  }
31656
32738
  finishRootParse(final) {
31657
- final && (this.clearDocumentCaches(), this.documentSource = void 0, this.semantics = void 0, this.finalized = !0);
32739
+ this.sourceRelationPrevious = void 0, this.sourceRelationCurrent = void 0, final && (this.clearDocumentCaches(), this.documentSource = void 0, this.semantics = void 0, this.finalized = !0);
31658
32740
  }
31659
32741
  resetForFinalAutoParse() {
31660
32742
  this.streamResetInCurrentRootParse || this.resetStreamOnly(), this.clearDocumentCaches();
@@ -31689,7 +32771,7 @@ var ParserRuntime = class {
31689
32771
  this.resetDocument(!0), parserRuntimes.delete(this.markdownIt);
31690
32772
  }
31691
32773
  clearDocumentCaches() {
31692
- this.safeMarkdown = void 0, this.tolerantMathBoundary = void 0, this.pendingExplicitMathTail = void 0, this.streamParseEnvs.clear(), this.topLevelStreamParseMode = void 0, this.structuredStream = void 0, this.siblingHtmlChildren = void 0, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.sourceLineOffsets = void 0;
32774
+ this.safeMarkdown = void 0, this.tolerantMathBoundary = void 0, this.pendingExplicitMathTail = void 0, this.streamParseEnvs.clear(), this.topLevelStreamParseMode = void 0, this.structuredStream = void 0, this.htmlPassIdentityPreserving = !1, this.siblingHtmlChildren = void 0, this.detailsStitchCache = /* @__PURE__ */ new WeakMap(), this.nodeSourceRanges = /* @__PURE__ */ new WeakMap(), this.sourceLineOffsets = void 0, this.sourceRelationPrevious = void 0, this.sourceRelationCurrent = void 0;
31693
32775
  }
31694
32776
  };
31695
32777
  function wrapMarkdownItBoundaries(md) {
@@ -31828,6 +32910,11 @@ function createSourceLineMapper(source, parsedSource) {
31828
32910
  };
31829
32911
  };
31830
32912
  }
32913
+ var closingTagBlankLineReCache = /* @__PURE__ */ new Map();
32914
+ function getClosingTagBlankLineRe(tag) {
32915
+ let re = closingTagBlankLineReCache.get(tag);
32916
+ return re || (re = new RegExp(String.raw`(^[\t ]*<\s*\/\s*${tag}\s*>[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`, "gim"), closingTagBlankLineReCache.size >= 64 && closingTagBlankLineReCache.clear(), closingTagBlankLineReCache.set(tag, re)), re;
32917
+ }
31831
32918
  function stripDanglingHtmlLikeTail(markdown) {
31832
32919
  let isWs = (ch) => ch === " " || ch === " " || ch === `
31833
32920
  ` || ch === "\r", isLikelyHtmlTagPrefix = (tail$1) => {
@@ -31888,8 +32975,8 @@ function stripDanglingHtmlLikeTail(markdown) {
31888
32975
  }
31889
32976
  }
31890
32977
  return !0;
31891
- }, isInsideFencedCodeBlock = (src, pos) => isInsideOpenMarkdownFenceBeforeOffset(src, pos), s = String(markdown ?? ""), lastLt = s.lastIndexOf("<");
31892
- if (lastLt === -1 || isInsideFencedCodeBlock(s, lastLt))
32978
+ }, s = String(markdown ?? ""), lastLt = s.lastIndexOf("<");
32979
+ if (lastLt === -1)
31893
32980
  return s;
31894
32981
  if (lastLt > 0) {
31895
32982
  let prev = s[lastLt - 1], prevIsWs = prev === " " || prev === " " || prev === `
@@ -31899,7 +32986,7 @@ function stripDanglingHtmlLikeTail(markdown) {
31899
32986
  }
31900
32987
  let tail = s.slice(lastLt);
31901
32988
  return tail.includes(">") || tail.length > 1 && (tail[1] === " " || tail[1] === " " || tail[1] === `
31902
- ` || tail[1] === "\r") || !isLikelyHtmlTagPrefix(tail) ? s : s.slice(0, lastLt);
32989
+ ` || tail[1] === "\r") || !isLikelyHtmlTagPrefix(tail) || isInsideOpenMarkdownFenceBeforeOffset(s, lastLt) ? s : s.slice(0, lastLt);
31903
32990
  }
31904
32991
  function ensureBlankLineBeforeInlineMultilineCustomHtmlBlocks(markdown, tags) {
31905
32992
  if (!markdown || !tags.length)
@@ -32445,10 +33532,8 @@ function normalizeStreamingCustomHtmlSource(markdown, customHtmlTags, isFinal) {
32445
33532
  if (customHtmlTags?.length && safeMarkdown.includes("<")) {
32446
33533
  let tags = normalizeCustomHtmlTags(customHtmlTags);
32447
33534
  if (tags.length && (safeMarkdown = ensureBlankLineBeforeInlineMultilineCustomHtmlBlocks(safeMarkdown, tags), safeMarkdown = normalizeCustomHtmlOpeningTagSameLine(safeMarkdown, tags), safeMarkdown = ensureBlankLineBeforeCustomHtmlBlocks(safeMarkdown, tags), safeMarkdown = ensureBlankLineAfterCustomHtmlCloseBeforeBlockMarkerSameLine(safeMarkdown, tags), safeMarkdown.includes("</")))
32448
- for (let tag of tags) {
32449
- let re = new RegExp(String.raw`(^[\t ]*<\s*\/\s*${tag}\s*>[\t ]*)(\r?\n)(?![\t ]*\r?\n|$)`, "gim");
32450
- safeMarkdown = safeMarkdown.replace(re, "$1$2$2");
32451
- }
33535
+ for (let tag of tags)
33536
+ safeMarkdown = safeMarkdown.replace(getClosingTagBlankLineRe(tag), "$1$2$2");
32452
33537
  }
32453
33538
  return isFinal || (safeMarkdown = stripDanglingHtmlLikeTail(safeMarkdown)), safeMarkdown;
32454
33539
  }
@@ -32475,7 +33560,7 @@ function transformStreamingSafeMarkdown(source, isFinal, options) {
32475
33560
  }
32476
33561
  function getSafeMarkdown(runtime, sourceMarkdown, isFinal, options) {
32477
33562
  let mode = `${isFinal ? "final" : "stream"}:${(options.customHtmlTags ?? []).join(",")}`, previous = options.isFragment ? void 0 : runtime.safeMarkdown, safeMarkdown;
32478
- if (!isFinal && !options.customHtmlTags?.length && previous && previous.mode === mode && sourceMarkdown.length >= previous.source.length && sourceMarkdown.startsWith(previous.source)) {
33563
+ if (!isFinal && !options.customHtmlTags?.length && previous && previous.mode === mode && sourceMarkdown.length >= previous.source.length && runtime.sourceExtends(previous.source, sourceMarkdown)) {
32479
33564
  let windowStart = Math.max(0, previous.source.length - SAFE_MARKDOWN_WINDOW_MARGIN - SAFE_MARKDOWN_WINDOW_OVERLAP), transformed = transformStreamingSafeMarkdown(sourceMarkdown.slice(windowStart), isFinal, options), overlapLength = previous.source.length - windowStart;
32480
33565
  safeMarkdown = transformed.length >= overlapLength && transformed.slice(0, overlapLength) === previous.safeMarkdown.slice(-overlapLength) ? previous.safeMarkdown.slice(0, previous.safeMarkdown.length - overlapLength) + transformed : transformStreamingSafeMarkdown(sourceMarkdown, isFinal, options);
32481
33566
  } else
@@ -32546,7 +33631,7 @@ function parseMarkdownWithContext(markdown, inputContext) {
32546
33631
  ...options,
32547
33632
  sourceLineMapper: options.includeSourceMap === !0 ? createSourceLineMapper(sourceMarkdown, safeMarkdown) : void 0,
32548
33633
  sourceMarkdown: safeMarkdown,
32549
- sourceLineOffsets: getCachedSourceLineOffsets(runtime, safeMarkdown),
33634
+ sourceLineOffsets: options.isFragment ? computeSourceLineOffsets(safeMarkdown) : getCachedSourceLineOffsets(runtime, safeMarkdown),
32550
33635
  customHtmlBlockCursor: 0
32551
33636
  }, result = processTopLevelTokensWithReuse(runtime, safeMarkdown, transformedTokens, internalOptions, {
32552
33637
  processTokens: (nextTokens, nextOptions) => processTokensWithTiming(nextTokens, nextOptions, timing),
@@ -32568,9 +33653,18 @@ function parseMarkdownWithContext(markdown, inputContext) {
32568
33653
  getInternalNodeSourceRange: (node) => getInternalNodeSourceRange(node, runtime),
32569
33654
  markdownIt: md,
32570
33655
  parseFragment: (fragment, fragmentOptions) => parseMarkdownWithContext(fragment, fragmentOptions)
32571
- };
32572
- result = mergeSplitTopLevelHtmlBlocks(result, isFinal, safeMarkdown, htmlStructureContext, internalOptions), result = combineStructuredDetailsHtmlBlocks(result, safeMarkdown, htmlStructureContext, internalOptions, isFinal)[0], result = structureGenericHtmlBlockChildren(result, htmlStructureContext, internalOptions, isFinal, tailStart), timing && addTiming(timing, "htmlBlockPassesMs", getParserNow() - htmlPassesStartedAt);
32573
- }
33656
+ }, canReuseHtmlPrefix = tailStart > 0 && runtime.htmlPassIdentityPreserving, tailSourceStart = canReuseHtmlPrefix ? getInternalNodeSourceRange(result[tailStart], runtime)?.start : void 0, hasDetailsInput = !1;
33657
+ for (let i = canReuseHtmlPrefix ? tailStart : 0; i < result.length; i++) {
33658
+ let node = result[i];
33659
+ if (node.type === "html_block" && String(node.tag ?? "").toLowerCase() === "details") {
33660
+ hasDetailsInput = !0;
33661
+ break;
33662
+ }
33663
+ }
33664
+ let useHtmlTail = canReuseHtmlPrefix && !hasDetailsInput && tailSourceStart != null, prefix = useHtmlTail ? result.slice(0, tailStart) : [], htmlInput = useHtmlTail ? result.slice(tailStart) : result, htmlSourceStart = useHtmlTail ? tailSourceStart : 0, htmlResult = mergeSplitTopLevelHtmlBlocks(htmlInput, isFinal, safeMarkdown, htmlStructureContext, internalOptions, htmlSourceStart), mergeIdentityPreserving = htmlResult.length === htmlInput.length && htmlResult.every((node, index) => node === htmlInput[index]);
33665
+ hasDetailsInput && (htmlResult = combineStructuredDetailsHtmlBlocks(htmlResult, safeMarkdown, htmlStructureContext, internalOptions, isFinal, htmlSourceStart)[0]), htmlResult = structureGenericHtmlBlockChildren(htmlResult, htmlStructureContext, internalOptions, isFinal), result = useHtmlTail ? prefix.concat(htmlResult) : htmlResult, runtime.htmlPassIdentityPreserving = !hasDetailsInput && mergeIdentityPreserving, timing && addTiming(timing, "htmlBlockPassesMs", getParserNow() - htmlPassesStartedAt);
33666
+ } else
33667
+ runtime.htmlPassIdentityPreserving = !0;
32574
33668
  return isFinal && finalizeHtmlBlockLoading(result), result = applyPostTransformNodes(result, options), options.debug && console.log("Parsed Markdown Tree Structure:", result), finishTimedParse(result, timing, parseStartedAt);
32575
33669
  }
32576
33670
  function parseMarkdownToStructure(markdown, md, options = {}) {
@@ -32708,11 +33802,13 @@ function getMarkdown(msgId = `editor-${Date.now()}`, options = {}) {
32708
33802
  md.use(applyInlinePairs), md.use(sup_plugin), md.use(ins_plugin$1);
32709
33803
  let checkboxModule = import_markdown_it_task_checkbox, markdownItCheckboxPlugin = checkboxModule.default ?? checkboxModule;
32710
33804
  md.use(markdownItCheckboxPlugin), md.use(ins_plugin), md.use(footnote_plugin), md.core.ruler.after("block", "mark_fence_closed", (state) => {
32711
- let s = state, src = s.src, envFinal = !!s.env?.__markstreamFinal, lines = src.split(/\r?\n/);
33805
+ let s = state, src = s.src, envFinal = !!s.env?.__markstreamFinal, lines;
32712
33806
  for (let token of s.tokens) {
32713
33807
  if (token.type !== "fence" || !token.map || !token.markup)
32714
33808
  continue;
32715
- let openLine = token.map[0], endLine = token.map[1], markup = token.markup, marker = markup[0], minLen = markup.length, line = lines[Math.max(0, endLine - 1)] ?? "", i = 0;
33809
+ let openLine = token.map[0], endLine = token.map[1], markup = token.markup, marker = markup[0], minLen = markup.length, lineIdx = Math.max(0, endLine - 1);
33810
+ lines ?? (lines = src.split(/\r?\n/));
33811
+ let line = lines[lineIdx] ?? "", i = 0;
32716
33812
  for (; i < line.length && (line[i] === " " || line[i] === " "); )
32717
33813
  i++;
32718
33814
  let count = 0;
@@ -34981,7 +36077,11 @@ var TVirtualMarkdown = (0, import_vue33.defineComponent)({
34981
36077
  return withTextWidthProvider(
34982
36078
  widthProvider,
34983
36079
  () => terminalSelectionRowSpans(range, cols, rows.value.length).map((span) => {
34984
- let text2 = sliceByCellsRange(rows.value[span.y]?.plainText ?? "", span.x0, span.x1);
36080
+ let text2 = sliceByCellsRangeForSelection(
36081
+ rows.value[span.y]?.plainText ?? "",
36082
+ span.x0,
36083
+ span.x1
36084
+ );
34985
36085
  return span.x1 >= cols ? text2.trimEnd() : text2;
34986
36086
  }).join(`
34987
36087
  `)