@vectojs/markdown 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -23,7 +33,9 @@ __export(index_exports, {
23
33
  CodeBlock: () => CodeBlock,
24
34
  Markdown: () => Markdown,
25
35
  codeAtlas: () => codeAtlas,
26
- codeAtlasStats: () => codeAtlasStats
36
+ codeAtlasStats: () => codeAtlasStats,
37
+ isMathJaxReady: () => isMathJaxReady,
38
+ preloadMathJax: () => preloadMathJax
27
39
  });
28
40
  module.exports = __toCommonJS(index_exports);
29
41
 
@@ -58,7 +70,10 @@ var StreamControllerImpl = class {
58
70
  this.signal = options.signal;
59
71
  this.onSignalAbort = () => this.abort(this.signal?.reason);
60
72
  if (this.signal?.aborted) this.abort(this.signal.reason);
61
- else this.signal?.addEventListener("abort", this.onSignalAbort, { once: true });
73
+ else
74
+ this.signal?.addEventListener("abort", this.onSignalAbort, {
75
+ once: true
76
+ });
62
77
  }
63
78
  host;
64
79
  maxBufferedChars;
@@ -146,10 +161,33 @@ var StreamControllerImpl = class {
146
161
  return closePromise;
147
162
  }
148
163
  this.currentState = "closed";
149
- this.cleanup();
150
- this.resolveClose?.();
151
- this.resolveClose = null;
152
- this.rejectClose = null;
164
+ let settled;
165
+ try {
166
+ settled = this.host.onClose?.();
167
+ } catch (error) {
168
+ this.cleanup();
169
+ this.rejectPendingClose(error);
170
+ return closePromise;
171
+ }
172
+ if (settled === void 0) {
173
+ this.cleanup();
174
+ this.resolveClose?.();
175
+ this.resolveClose = null;
176
+ this.rejectClose = null;
177
+ return closePromise;
178
+ }
179
+ void Promise.resolve(settled).then(
180
+ () => {
181
+ this.cleanup();
182
+ this.resolveClose?.();
183
+ this.resolveClose = null;
184
+ this.rejectClose = null;
185
+ },
186
+ (error) => {
187
+ this.cleanup();
188
+ this.rejectPendingClose(error);
189
+ }
190
+ );
153
191
  return closePromise;
154
192
  }
155
193
  abort(reason) {
@@ -415,16 +453,10 @@ function createStreamController(host, options = {}) {
415
453
  }
416
454
 
417
455
  // src/Markdown.ts
418
- var import_mathjax = require("mathjax-full/js/mathjax.js");
419
- var import_tex = require("mathjax-full/js/input/tex.js");
420
- var import_svg = require("mathjax-full/js/output/svg.js");
421
- var import_liteAdaptor = require("mathjax-full/js/adaptors/liteAdaptor.js");
422
- var import_html = require("mathjax-full/js/handlers/html.js");
423
- var import_AllPackages = require("mathjax-full/js/input/tex/AllPackages.js");
424
456
  var import_ui = require("@vectojs/ui");
425
457
 
426
458
  // src/MarkdownWorkerSource.ts
427
- var WORKER_SOURCE_STRING = '"use strict";(()=>{function U(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var A=U();function he(r){A=r}var T={exec:()=>null};function L(r){let e=[];return t=>{let s=Math.max(0,Math.min(3,t-1)),n=e[s];return n||(n=r(s),e[s]=n),n}}function g(r,e=""){let t=typeof r=="string"?r:r.source,s={replace:(n,i)=>{let a=typeof i=="string"?i:i.source;return a=a.replace(b.caret,"$1"),t=t.replace(n,a),s},getRegex:()=>new RegExp(t,e)};return s}var me=((r="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+r)}catch{return!1}})(),b={codeRemoveIndent:/^(?: {1,4}| {0,3}\\t)/gm,outputLinkReplace:/\\\\([\\[\\]])/g,indentCodeCompensation:/^(\\s+)(?:```)/,beginningSpace:/^\\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\\n/g,tabCharGlobal:/\\t/g,multipleSpaceGlobal:/\\s+/g,blankLine:/^[ \\t]*$/,doubleBlankLine:/\\n[ \\t]*\\n[ \\t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^\'"]*[^\\s])\\s+([\'"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,escapeTest:/[&<>"\']/,escapeReplace:/[&<>"\']/g,escapeTestNoEncode:/[<>"\']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>"\']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:r=>new RegExp(`^( {0,3}${r})((?:[ ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:L(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ ][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:L(r=>new RegExp(`^ {0,${r}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:L(r=>new RegExp(`^ {0,${r}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:L(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:L(r=>new RegExp(`^ {0,${r}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:L(r=>new RegExp(`^ {0,${r}}>`))},ye=/^(?:[ \\t]*(?:\\n|$))+/,$e=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,M=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Se=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,F=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,pe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,ue=g(pe).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,"").getRegex(),Te=g(pe).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),V=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,ze=/^[^\\n]+/,J=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Ae=g(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace("label",J).replace("title",/(?:"(?:\\\\"?|[^"\\\\])*"|\'[^\'\\n]*(?:\\n[^\'\\n]+)*\\n?\'|\\([^()]*\\))/).getRegex(),Le=g(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,F).getRegex(),j="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,_e=g("^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n*|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n*|$)|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n*|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n*|$)|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$))","i").replace("comment",K).replace("tag",j).replace("attribute",/ +[a-zA-Z:_][\\w.:-]*(?: *= *"[^"\\n]*"| *= *\'[^\'\\n]*\'| *= *[^\\s"\'=<>`]+)?/).getRegex(),ge=r=>g(V).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list",r).replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex(),Pe=ge(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),ve=ge(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),Ie=g(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace("paragraph",ve).getRegex(),Y={blockquote:Ie,code:$e,def:Ae,fences:Re,heading:Se,hr:M,html:_e,lheading:ue,list:Le,newline:ye,paragraph:Pe,table:T,text:ze},ne=g("^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)").replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\\\t]").replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex(),Ce={...Y,lheading:Te,table:ne,paragraph:g(V).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("table",ne).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]").replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex()},Ee={...Y,html:g(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:"[^"]*"|\'[^\']*\'|\\\\s[^\'"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b").getRegex(),def:/^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +(["(][^\\n]+[")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:T,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:g(V).replace("hr",M).replace("heading",` *#{1,6} *[^\n]`).replace("lheading",ue).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Me=/^\\\\([!"#$%&\'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,Be=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ke=/^( {2,}|\\\\)\\n(?!\\s*$)/,qe=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,_=/[\\p{P}\\p{S}]/u,H=/[\\s\\p{P}\\p{S}]/u,ee=/[^\\s\\p{P}\\p{S}]/u,Ze=g(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,H).getRegex(),fe=/(?!~)[\\p{P}\\p{S}]/u,De=/(?!~)[\\s\\p{P}\\p{S}]/u,Qe=/(?:[^\\s\\p{P}\\p{S}]|~)/u,Ne=g(/link|precode-code|html/,"g").replace("link",/\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace("precode-",me?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),de=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,je=g(de,"u").replace(/punct/g,_).getRegex(),He=g(de,"u").replace(/punct/g,fe).getRegex(),xe="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)",Oe=g(xe,"gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Ge=g(xe,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,De).replace(/punct/g,fe).getRegex(),We=g("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Xe=g(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,_).getRegex(),Ue="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Fe=g(Ue,"gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Ve=g(/\\\\(punct)/,"gu").replace(/punct/g,_).getRegex(),Je=g(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&\'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ke=g(K).replace("(?:-->|$)","-->").getRegex(),Ye=g("^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>").replace("comment",Ke).replace("attribute",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*"[^"]*"|\\s*=\\s*\'[^\']*\'|\\s*=\\s*[^\\s"\'=<>`]+)?/).getRegex(),D=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,et=g(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",D).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|\'(?:\\\\\'?|[^\'\\\\])*\'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),be=g(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",D).replace("ref",J).getRegex(),we=g(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",J).getRegex(),tt=g("reflink|nolink(?!\\\\()","g").replace("reflink",be).replace("nolink",we).getRegex(),se=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,te={_backpedal:T,anyPunctuation:Ve,autolink:Je,blockSkip:Ne,br:ke,code:Be,del:T,delLDelim:T,delRDelim:T,emStrongLDelim:je,emStrongRDelimAst:Oe,emStrongRDelimUnd:We,escape:Me,link:et,nolink:we,punctuation:Ze,reflink:be,reflinkSearch:tt,tag:Ye,text:qe,url:T},rt={...te,link:g(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",D).getRegex(),reflink:g(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",D).getRegex()},G={...te,emStrongRDelimAst:Ge,emStrongLDelim:He,delLDelim:Xe,delRDelim:Fe,url:g(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",se).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_\'"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_\'"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:g(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-]+@)))/).replace("protocol",se).getRegex()},nt={...G,br:g(ke).replace("{2,}","*").getRegex(),text:g(G.text).replace("\\\\b_","\\\\b_| {2,}\\\\n").replace(/\\{2,\\}/g,"*").getRegex()},Z={normal:Y,gfm:Ce,pedantic:Ee},C={normal:te,gfm:G,breaks:nt,pedantic:rt},st={"&":"&amp;","<":"&lt;",">":"&gt;",\'"\':"&quot;","\'":"&#39;"},ie=r=>st[r];function y(r,e){if(e){if(b.escapeTest.test(r))return r.replace(b.escapeReplace,ie)}else if(b.escapeTestNoEncode.test(r))return r.replace(b.escapeReplaceNoEncode,ie);return r}function le(r){try{r=encodeURI(r).replace(b.percentDecode,"%")}catch{return null}return r}function ae(r,e){let t=r.replace(b.findPipe,(i,a,l)=>{let o=!1,c=a;for(;--c>=0&&l[c]==="\\\\";)o=!o;return o?"|":" |"}),s=t.split(b.splitPipe),n=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;n<s.length;n++)s[n]=s[n].trim().replace(b.slashPipe,"|");return s}function S(r,e,t){let s=r.length;if(s===0)return"";let n=0;for(;n<s;){let i=r.charAt(s-n-1);if(i===e&&!t)n++;else if(i!==e&&t)n++;else break}return r.slice(0,s-n)}function oe(r){let e=r.split(`\n`),t=e.length-1;for(;t>=0&&b.blankLine.test(e[t]);)t--;return e.length-t<=2?r:e.slice(0,t+1).join(`\n`)}function it(r,e){if(r.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<r.length;s++)if(r[s]==="\\\\")s++;else if(r[s]===e[0])t++;else if(r[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function lt(r,e=0){let t=e,s="";for(let n of r)if(n===" "){let i=4-t%4;s+=" ".repeat(i),t+=i}else s+=n,t++;return s}function ce(r,e,t,s,n){let i=e.href,a=e.title||null,l=r[1].replace(n.other.outputLinkReplace,"$1");s.state.inLink=!0;let o={type:r[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:a,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,o}function at(r,e,t){let s=r.match(t.other.indentCodeCompensation);if(s===null)return e;let n=s[1];return e.split(`\n`).map(i=>{let a=i.match(t.other.beginningSpace);if(a===null)return i;let[l]=a;return l.length>=n.length?i.slice(n.length):i}).join(`\n`)}var Q=class{options;rules;lexer;constructor(r){this.options=r||A}space(r){let e=this.rules.block.newline.exec(r);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(r){let e=this.rules.block.code.exec(r);if(e){let t=this.options.pedantic?e[0]:oe(e[0]),s=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:s}}}fences(r){let e=this.rules.block.fences.exec(r);if(e){let t=e[0],s=at(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(r){let e=this.rules.block.heading.exec(r);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let s=S(t,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(t=s.trim())}return{type:"heading",raw:S(e[0],`\n`),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(r){let e=this.rules.block.hr.exec(r);if(e)return{type:"hr",raw:S(e[0],`\n`)}}blockquote(r){let e=this.rules.block.blockquote.exec(r);if(e){let t=S(e[0],`\n`).split(`\n`),s="",n="",i=[];for(;t.length>0;){let a=!1,l=[],o;for(o=0;o<t.length;o++)if(this.rules.other.blockquoteStart.test(t[o]))l.push(t[o]),a=!0;else if(!a)l.push(t[o]);else break;t=t.slice(o);let c=l.join(`\n`),p=c.replace(this.rules.other.blockquoteSetextReplace,`\n $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}\n${c}`:c,n=n?`${n}\n${p}`:p;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=h,t.length===0)break;let u=i.at(-1);if(u?.type==="code")break;if(u?.type==="blockquote"){let x=u,f=x.raw+`\n`+t.join(`\n`),d=this.blockquote(f);i[i.length-1]=d,s=s.substring(0,s.length-x.raw.length)+d.raw,n=n.substring(0,n.length-x.text.length)+d.text;break}else if(u?.type==="list"){let x=u,f=x.raw+`\n`+t.join(`\n`),d=this.list(f);i[i.length-1]=d,s=s.substring(0,s.length-u.raw.length)+d.raw,n=n.substring(0,n.length-x.raw.length)+d.raw,t=f.substring(i.at(-1).raw.length).split(`\n`);continue}}return{type:"blockquote",raw:s,tokens:i,text:n}}}list(r){let e=this.rules.block.list.exec(r);if(e){let t=e[1].trim(),s=t.length>1,n={type:"list",raw:"",ordered:s,start:s?+t.slice(0,-1):"",loose:!1,items:[]};t=s?`\\\\d{1,9}\\\\${t.slice(-1)}`:`\\\\${t}`,this.options.pedantic&&(t=s?t:"[*+-]");let i=this.rules.other.listItemRegex(t),a=!1;for(;r;){let o=!1,c="",p="";if(!(e=i.exec(r))||this.rules.block.hr.test(r))break;c=e[0],r=r.substring(c.length);let h=lt(e[2].split(`\n`,1)[0],e[1].length),u=r.split(`\n`,1)[0],x=!h.trim(),f=0;if(this.options.pedantic?(f=2,p=h.trimStart()):x?f=e[1].length+1:(f=h.search(this.rules.other.nonSpaceChar),f=f>4?1:f,p=h.slice(f),f+=e[1].length),x&&this.rules.other.blankLine.test(u)&&(c+=u+`\n`,r=r.substring(u.length+1),o=!0),!o){let d=this.rules.other.nextBulletRegex(f),B=this.rules.other.hrRegex(f),$=this.rules.other.fencesBeginRegex(f),q=this.rules.other.headingBeginRegex(f),R=this.rules.other.htmlBeginRegex(f),v=this.rules.other.blockquoteBeginRegex(f);for(;r;){let O=r.split(`\n`,1)[0],I;if(u=O,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),I=u):I=u.replace(this.rules.other.tabCharGlobal," "),$.test(u)||q.test(u)||R.test(u)||v.test(u)||d.test(u)||B.test(u))break;if(I.search(this.rules.other.nonSpaceChar)>=f||!u.trim())p+=`\n`+I.slice(f);else{if(x||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||$.test(h)||q.test(h)||B.test(h))break;p+=`\n`+u}x=!u.trim(),c+=O+`\n`,r=r.substring(O.length+1),h=I.slice(f)}}n.loose||(a?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(a=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),n.raw+=c}let l=n.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let o of n.items){this.lexer.state.top=!1,o.tokens=this.lexer.blockTokens(o.text,[]);let c=o.tokens[0];if(o.task&&(c?.type==="text"||c?.type==="paragraph")){o.text=o.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(o.raw);if(p){let h={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};o.checked=h.checked,n.loose?o.tokens[0]&&["paragraph","text"].includes(o.tokens[0].type)&&"tokens"in o.tokens[0]&&o.tokens[0].tokens?(o.tokens[0].raw=h.raw+o.tokens[0].raw,o.tokens[0].text=h.raw+o.tokens[0].text,o.tokens[0].tokens.unshift(h)):o.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):o.tokens.unshift(h)}}else o.task&&(o.task=!1);if(!n.loose){let p=o.tokens.filter(u=>u.type==="space"),h=p.length>0&&p.some(u=>this.rules.other.anyLine.test(u.raw));n.loose=h}}if(n.loose)for(let o of n.items){o.loose=!0;for(let c of o.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(r){let e=this.rules.block.html.exec(r);if(e){let t=oe(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(r){let e=this.rules.block.def.exec(r);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:S(e[0],`\n`),href:s,title:n}}}table(r){let e=this.rules.block.table.exec(r);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=ae(e[1]),s=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`\n`):[],i={type:"table",raw:S(e[0],`\n`),header:[],align:[],rows:[]};if(t.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a<t.length;a++)i.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:i.align[a]});for(let a of n)i.rows.push(ae(a,i.header.length).map((l,o)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[o]})));return i}}lheading(r){let e=this.rules.block.lheading.exec(r);if(e){let t=e[1].trim();return{type:"heading",raw:S(e[0],`\n`),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(r){let e=this.rules.block.paragraph.exec(r);if(e){let t=e[1].charAt(e[1].length-1)===`\n`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(r){let e=this.rules.block.text.exec(r);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(r){let e=this.rules.inline.escape.exec(r);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(r){let e=this.rules.inline.tag.exec(r);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(r){let e=this.rules.inline.link.exec(r);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let i=S(t.slice(0,-1),"\\\\");if((t.length-i.length)%2===0)return}else{let i=it(e[2],"()");if(i===-2)return;if(i>-1){let a=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,a).trim(),e[3]=""}}let s=e[2],n="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],n=i[3])}else n=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?s=s.slice(1):s=s.slice(1,-1)),ce(e,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(r,e){let t;if((t=this.rules.inline.reflink.exec(r))||(t=this.rules.inline.nolink.exec(r))){let s=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[s.toLowerCase()];if(!n){let i=t[0].charAt(0);return{type:"text",raw:i,text:i}}return ce(t,n,t[0],this.lexer,this.rules)}}emStrong(r,e,t=""){let s=this.rules.inline.emStrongLDelim.exec(r);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!t||this.rules.inline.punctuation.exec(t))){let n=[...s[0]].length-1,i,a,l=n,o=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*r.length+n);(s=c.exec(e))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(a=[...i].length,s[3]||s[4]){l+=a;continue}else if((s[5]||s[6])&&n%3&&!((n+a)%3)){o+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l+o);let p=[...s[0]][0].length,h=r.slice(0,n+s.index+p+a);if(Math.min(n,a)%2){let x=h.slice(1,-1);return{type:"em",raw:h,text:x,tokens:this.lexer.inlineTokens(x)}}let u=h.slice(2,-2);return{type:"strong",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}codespan(r){let e=this.rules.inline.code.exec(r);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(t),n=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return s&&n&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(r){let e=this.rules.inline.br.exec(r);if(e)return{type:"br",raw:e[0]}}del(r,e,t=""){let s=this.rules.inline.delLDelim.exec(r);if(s&&(!s[1]||!t||this.rules.inline.punctuation.exec(t))){let n=[...s[0]].length-1,i,a,l=n,o=this.rules.inline.delRDelim;for(o.lastIndex=0,e=e.slice(-1*r.length+n);(s=o.exec(e))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(a=[...i].length,a!==n))continue;if(s[3]||s[4]){l+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l);let c=[...s[0]][0].length,p=r.slice(0,n+s.index+c+a),h=p.slice(n,-n);return{type:"del",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(r){let e=this.rules.inline.autolink.exec(r);if(e){let t,s;return e[2]==="@"?(t=e[1],s="mailto:"+t):(t=e[1],s=t),{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}url(r){let e;if(e=this.rules.inline.url.exec(r)){let t,s;if(e[2]==="@")t=e[0],s="mailto:"+t;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);t=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(r){let e=this.rules.inline.text.exec(r);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},w=class W{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||A,this.options.tokenizer=this.options.tokenizer||new Q,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:b,block:Z.normal,inline:C.normal};this.options.pedantic?(t.block=Z.pedantic,t.inline=C.pedantic):this.options.gfm&&(t.block=Z.gfm,this.options.breaks?t.inline=C.breaks:t.inline=C.gfm),this.tokenizer.rules=t}static get rules(){return{block:Z,inline:C}}static lex(e,t){return new W(t).lex(e)}static lexInline(e,t){return new W(t).inlineTokens(e)}lex(e){e=e.replace(b.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let s=this.inlineQueue[t];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(b.tabCharGlobal," ").replace(b.spaceLine,""));let n=1/0;for(;e;){if(e.length<n)n=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(l=>(i=l.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let l=t.at(-1);i.raw.length===1&&l!==void 0?l.raw+=`\n`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let l=1/0,o=e.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},o),typeof c=="number"&&c>=0&&(l=Math.min(l,c))}),l<1/0&&l>=0&&(a=e.substring(0,l+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let l=t.at(-1);s&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i),s=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let s=e;if(this.tokens.links){let l=Object.keys(this.tokens.links);l.length>0&&(s=s.replace(this.tokenizer.rules.inline.reflinkSearch,o=>l.includes(o.slice(o.lastIndexOf("[")+1,-1))?"["+"a".repeat(o.length-2)+"]":o))}s=s.replace(this.tokenizer.rules.inline.anyPunctuation,"++"),s=s.replace(this.tokenizer.rules.inline.blockSkip,(l,o,c)=>{let p=c?c.length:0;return l.slice(0,p)+"["+"a".repeat(l.length-p-2)+"]"}),s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,i="",a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(i=""),n=!1;let l;if(this.options.extensions?.inline?.some(c=>(l=c.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let c=t.at(-1);l.type==="text"&&c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,s,i)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e,s,i)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let o=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),h;this.options.extensions.startInline.forEach(u=>{h=u.call({lexer:this},p),typeof h=="number"&&h>=0&&(c=Math.min(c,h))}),c<1/0&&c>=0&&(o=e.substring(0,c+1))}if(l=this.tokenizer.inlineText(o)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(i=l.raw.slice(-1)),n=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},N=class{options;parser;constructor(r){this.options=r||A}space(r){return""}code({text:r,lang:e,escaped:t}){let s=(e||"").match(b.notSpaceStart)?.[0],n=r.replace(b.endingNewline,"")+`\n`;return s?\'<pre><code class="language-\'+y(s)+\'">\'+(t?n:y(n,!0))+`</code></pre>\n`:"<pre><code>"+(t?n:y(n,!0))+`</code></pre>\n`}blockquote({tokens:r}){return`<blockquote>\n${this.parser.parse(r)}</blockquote>\n`}html({text:r}){return r}def(r){return""}heading({tokens:r,depth:e}){return`<h${e}>${this.parser.parseInline(r)}</h${e}>\n`}hr(r){return`<hr>\n`}list(r){let e=r.ordered,t=r.start,s="";for(let a=0;a<r.items.length;a++){let l=r.items[a];s+=this.listitem(l)}let n=e?"ol":"ul",i=e&&t!==1?\' start="\'+t+\'"\':"";return"<"+n+i+`>\n`+s+"</"+n+`>\n`}listitem(r){return`<li>${this.parser.parse(r.tokens)}</li>\n`}checkbox({checked:r}){return"<input "+(r?\'checked="" \':"")+\'disabled="" type="checkbox"> \'}paragraph({tokens:r}){return`<p>${this.parser.parseInline(r)}</p>\n`}table(r){let e="",t="";for(let n=0;n<r.header.length;n++)t+=this.tablecell(r.header[n]);e+=this.tablerow({text:t});let s="";for(let n=0;n<r.rows.length;n++){let i=r.rows[n];t="";for(let a=0;a<i.length;a++)t+=this.tablecell(i[a]);s+=this.tablerow({text:t})}return s&&(s=`<tbody>${s}</tbody>`),`<table>\n<thead>\n`+e+`</thead>\n`+s+`</table>\n`}tablerow({text:r}){return`<tr>\n${r}</tr>\n`}tablecell(r){let e=this.parser.parseInline(r.tokens),t=r.header?"th":"td";return(r.align?`<${t} align="${r.align}">`:`<${t}>`)+e+`</${t}>\n`}strong({tokens:r}){return`<strong>${this.parser.parseInline(r)}</strong>`}em({tokens:r}){return`<em>${this.parser.parseInline(r)}</em>`}codespan({text:r}){return`<code>${y(r,!0)}</code>`}br(r){return"<br>"}del({tokens:r}){return`<del>${this.parser.parseInline(r)}</del>`}link({href:r,title:e,tokens:t}){let s=this.parser.parseInline(t),n=le(r);if(n===null)return s;r=n;let i=\'<a href="\'+r+\'"\';return e&&(i+=\' title="\'+y(e)+\'"\'),i+=">"+s+"</a>",i}image({href:r,title:e,text:t,tokens:s}){s&&(t=this.parser.parseInline(s,this.parser.textRenderer));let n=le(r);if(n===null)return y(t);r=n;let i=`<img src="${r}" alt="${y(t)}"`;return e&&(i+=` title="${y(e)}"`),i+=">",i}text(r){return"tokens"in r&&r.tokens?this.parser.parseInline(r.tokens):"escaped"in r&&r.escaped?r.text:y(r.text)}},re=class{strong({text:r}){return r}em({text:r}){return r}codespan({text:r}){return r}del({text:r}){return r}html({text:r}){return r}text({text:r}){return r}link({text:r}){return""+r}image({text:r}){return""+r}br(){return""}checkbox({raw:r}){return r}},m=class X{options;renderer;textRenderer;constructor(e){this.options=e||A,this.options.renderer=this.options.renderer||new N,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new re}static parse(e,t){return new X(t).parse(e)}static parseInline(e,t){return new X(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let s=0;s<e.length;s++){let n=e[s];if(this.options.extensions?.renderers?.[n.type]){let a=n,l=this.options.extensions.renderers[a.type].call({parser:this},a);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(a.type)){t+=l||"";continue}}let i=n;switch(i.type){case"space":{t+=this.renderer.space(i);break}case"hr":{t+=this.renderer.hr(i);break}case"heading":{t+=this.renderer.heading(i);break}case"code":{t+=this.renderer.code(i);break}case"table":{t+=this.renderer.table(i);break}case"blockquote":{t+=this.renderer.blockquote(i);break}case"list":{t+=this.renderer.list(i);break}case"checkbox":{t+=this.renderer.checkbox(i);break}case"html":{t+=this.renderer.html(i);break}case"def":{t+=this.renderer.def(i);break}case"paragraph":{t+=this.renderer.paragraph(i);break}case"text":{t+=this.renderer.text(i);break}default:{let a=\'Token with "\'+i.type+\'" type was not found.\';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let s="";for(let n=0;n<e.length;n++){let i=e[n];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){s+=l||"";continue}}let a=i;switch(a.type){case"escape":{s+=t.text(a);break}case"html":{s+=t.html(a);break}case"link":{s+=t.link(a);break}case"image":{s+=t.image(a);break}case"checkbox":{s+=t.checkbox(a);break}case"strong":{s+=t.strong(a);break}case"em":{s+=t.em(a);break}case"codespan":{s+=t.codespan(a);break}case"br":{s+=t.br(a);break}case"del":{s+=t.del(a);break}case"text":{s+=t.text(a);break}default:{let l=\'Token with "\'+a.type+\'" type was not found.\';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},E=class{options;block;constructor(r){this.options=r||A}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(r){return r}postprocess(r){return r}processAllTokens(r){return r}emStrongMask(r){return r}provideLexer(r=this.block){return r?w.lex:w.lexInline}provideParser(r=this.block){return r?m.parse:m.parseInline}},ot=class{defaults=U();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=m;Renderer=N;TextRenderer=re;Lexer=w;Tokenizer=Q;Hooks=E;constructor(...r){this.use(...r)}walkTokens(r,e){let t=[];for(let s of r)switch(t=t.concat(e.call(this,s)),s.type){case"table":{let n=s;for(let i of n.header)t=t.concat(this.walkTokens(i.tokens,e));for(let i of n.rows)for(let a of i)t=t.concat(this.walkTokens(a.tokens,e));break}case"list":{let n=s;t=t.concat(this.walkTokens(n.items,e));break}default:{let n=s;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(i=>{let a=n[i].flat(1/0);t=t.concat(this.walkTokens(a,e))}):n.tokens&&(t=t.concat(this.walkTokens(n.tokens,e)))}}return t}use(...r){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return r.forEach(t=>{let s={...t};if(s.async=this.defaults.async||s.async||!1,t.extensions&&(t.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let i=e.renderers[n.name];i?e.renderers[n.name]=function(...a){let l=n.renderer.apply(this,a);return l===!1&&(l=i.apply(this,a)),l}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be \'block\' or \'inline\'");let i=e[n.level];i?i.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),s.extensions=e),t.renderer){let n=this.defaults.renderer||new N(this.defaults);for(let i in t.renderer){if(!(i in n))throw new Error(`renderer \'${i}\' does not exist`);if(["options","parser"].includes(i))continue;let a=i,l=t.renderer[a],o=n[a];n[a]=(...c)=>{let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p||""}}s.renderer=n}if(t.tokenizer){let n=this.defaults.tokenizer||new Q(this.defaults);for(let i in t.tokenizer){if(!(i in n))throw new Error(`tokenizer \'${i}\' does not exist`);if(["options","rules","lexer"].includes(i))continue;let a=i,l=t.tokenizer[a],o=n[a];n[a]=(...c)=>{let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p}}s.tokenizer=n}if(t.hooks){let n=this.defaults.hooks||new E;for(let i in t.hooks){if(!(i in n))throw new Error(`hook \'${i}\' does not exist`);if(["options","block"].includes(i))continue;let a=i,l=t.hooks[a],o=n[a];E.passThroughHooks.has(i)?n[a]=c=>{if(this.defaults.async&&E.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await l.call(n,c);return o.call(n,h)})();let p=l.call(n,c);return o.call(n,p)}:n[a]=(...c)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(n,c);return h===!1&&(h=await o.apply(n,c)),h})();let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p}}s.hooks=n}if(t.walkTokens){let n=this.defaults.walkTokens,i=t.walkTokens;s.walkTokens=function(a){let l=[];return l.push(i.call(this,a)),n&&(l=l.concat(n.call(this,a))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(r){return this.defaults={...this.defaults,...r},this}lexer(r,e){return w.lex(r,e??this.defaults)}parser(r,e){return m.parse(r,e??this.defaults)}parseMarkdown(r){return(e,t)=>{let s={...t},n={...this.defaults,...s},i=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=r),n.async)return(async()=>{let a=n.hooks?await n.hooks.preprocess(e):e,l=await(n.hooks?await n.hooks.provideLexer(r):r?w.lex:w.lexInline)(a,n),o=n.hooks?await n.hooks.processAllTokens(l):l;n.walkTokens&&await Promise.all(this.walkTokens(o,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(r):r?m.parse:m.parseInline)(o,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(i);try{n.hooks&&(e=n.hooks.preprocess(e));let a=(n.hooks?n.hooks.provideLexer(r):r?w.lex:w.lexInline)(e,n);n.hooks&&(a=n.hooks.processAllTokens(a)),n.walkTokens&&this.walkTokens(a,n.walkTokens);let l=(n.hooks?n.hooks.provideParser(r):r?m.parse:m.parseInline)(a,n);return n.hooks&&(l=n.hooks.postprocess(l)),l}catch(a){return i(a)}}}onError(r,e){return t=>{if(t.message+=`\nPlease report this to https://github.com/markedjs/marked.`,r){let s="<p>An error occurred:</p><pre>"+y(t.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(t);throw t}}},z=new ot;function k(r,e){return z.parse(r,e)}k.options=k.setOptions=function(r){return z.setOptions(r),k.defaults=z.defaults,he(k.defaults),k};k.getDefaults=U;k.defaults=A;k.use=function(...r){return z.use(...r),k.defaults=z.defaults,he(k.defaults),k};k.walkTokens=function(r,e){return z.walkTokens(r,e)};k.parseInline=z.parseInline;k.Parser=m;k.parser=m.parse;k.Renderer=N;k.TextRenderer=re;k.Lexer=w;k.lexer=w.lex;k.Tokenizer=Q;k.Hooks=E;k.parse=k;var ut=k.options,gt=k.setOptions,kt=k.use,ft=k.walkTokens,dt=k.parseInline;var xt=m.parse,bt=w.lex;var ct=0;function ht(r){if(typeof r!="string"||typeof performance.mark!="function"||typeof performance.measure!="function")return null;let e=ct++,t={name:r,startMark:`${r}:start:${e}`,endMark:`${r}:end:${e}`};try{return performance.mark(t.startMark),t}catch{return null}}function pt(r){if(r)try{performance.mark(r.endMark),performance.measure(r.name,r.startMark,r.endMark)}catch{}finally{try{performance.clearMarks?.(r.startMark),performance.clearMarks?.(r.endMark)}catch{}}}k.use({extensions:[{name:"inlineMath",level:"inline",start(r){return r.match(/(?<![\\\\$])\\$(?![$\\s])/)?.index},tokenizer(r){let e=/^\\$(?![$\\s\\d])((?:\\\\\\$|[^$\\n])*?)(?<!\\s)\\$(?!\\d)/.exec(r);if(e)return{type:"inlineMath",raw:e[0],text:e[1].trim()}},renderer(r){return r.raw}}]});var P=new Map;self.onmessage=r=>{let e=r.data;if(typeof e!="object"||e===null)return;let{id:t,text:s,append:n,expectedLength:i,oldRaws:a,instance:l,baseVersion:o,dispose:c,userTimingName:p}=e;if(c===!0){typeof l=="string"&&P.delete(l);return}let h=typeof l=="string"?l:null,u=typeof o=="number"?o:null,x,f=null;if(typeof n=="string"){if(h===null||u===null){self.postMessage({id:t,needResync:!0});return}let d=P.get(h);if(!d||d.version!==u){self.postMessage({id:t,needResync:!0});return}if(x=d.source+n,typeof i=="number"&&x.length!==i){P.delete(h),self.postMessage({id:t,needResync:!0});return}f=d.raws}else if(typeof s=="string"){if(x=s,Array.isArray(a))f=a;else if(h!==null&&u!==null){let d=P.get(h);if(d&&d.version===u)f=d.raws;else{self.postMessage({id:t,needResync:!0});return}}}else return;try{let d=typeof p=="string"?ht(p):null,B=performance.now(),$;try{$=k.lexer(x)}finally{d&&pt(d)}let q=performance.now()-B,R=0;if(f){let v=Math.min(f.length,$.length);for(;R<v&&f[R]===$[R].raw;R++);}h!==null&&u!==null&&P.set(h,{version:u+1,raws:$.map(v=>v.raw),source:x}),self.postMessage({id:t,matchLen:R,tail:$.slice(R),lexerMs:q,sourceCharsLexed:x.length})}catch(d){h!==null&&P.delete(h),self.postMessage({id:t,error:String(d)})}};})();\n';
459
+ var WORKER_SOURCE_STRING = '"use strict";(()=>{function U(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var A=U();function he(r){A=r}var T={exec:()=>null};function L(r){let e=[];return t=>{let s=Math.max(0,Math.min(3,t-1)),n=e[s];return n||(n=r(s),e[s]=n),n}}function g(r,e=""){let t=typeof r=="string"?r:r.source,s={replace:(n,i)=>{let a=typeof i=="string"?i:i.source;return a=a.replace(b.caret,"$1"),t=t.replace(n,a),s},getRegex:()=>new RegExp(t,e)};return s}var me=((r="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+r)}catch{return!1}})(),b={codeRemoveIndent:/^(?: {1,4}| {0,3}\\t)/gm,outputLinkReplace:/\\\\([\\[\\]])/g,indentCodeCompensation:/^(\\s+)(?:```)/,beginningSpace:/^\\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\\n/g,tabCharGlobal:/\\t/g,multipleSpaceGlobal:/\\s+/g,blankLine:/^[ \\t]*$/,doubleBlankLine:/\\n[ \\t]*\\n[ \\t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^\'"]*[^\\s])\\s+([\'"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,escapeTest:/[&<>"\']/,escapeReplace:/[&<>"\']/g,escapeTestNoEncode:/[<>"\']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>"\']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:r=>new RegExp(`^( {0,3}${r})((?:[ ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:L(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ ][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:L(r=>new RegExp(`^ {0,${r}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:L(r=>new RegExp(`^ {0,${r}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:L(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:L(r=>new RegExp(`^ {0,${r}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:L(r=>new RegExp(`^ {0,${r}}>`))},ye=/^(?:[ \\t]*(?:\\n|$))+/,$e=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,Re=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,M=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Se=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,F=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,pe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,ue=g(pe).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,"").getRegex(),Te=g(pe).replace(/bull/g,F).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\\s|$)/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),V=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,ze=/^[^\\n]+/,J=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Ae=g(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace("label",J).replace("title",/(?:"(?:\\\\"?|[^"\\\\])*"|\'[^\'\\n]*(?:\\n[^\'\\n]+)*\\n?\'|\\([^()]*\\))/).getRegex(),Le=g(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,F).getRegex(),j="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",K=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,_e=g("^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n*|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n*|$)|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n*|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n*|$)|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ ]*)+\\\\n|$))","i").replace("comment",K).replace("tag",j).replace("attribute",/ +[a-zA-Z:_][\\w.:-]*(?: *= *"[^"\\n]*"| *= *\'[^\'\\n]*\'| *= *[^\\s"\'=<>`]+)?/).getRegex(),ge=r=>g(V).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list",r).replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex(),Pe=ge(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),ve=ge(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),Ie=g(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace("paragraph",ve).getRegex(),Y={blockquote:Ie,code:$e,def:Ae,fences:Re,heading:Se,hr:M,html:_e,lheading:ue,list:Le,newline:ye,paragraph:Pe,table:T,text:ze},ne=g("^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)").replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\\\t]").replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex(),Ce={...Y,lheading:Te,table:ne,paragraph:g(V).replace("hr",M).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("table",ne).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~~~)[^\\\\n]*\\\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]").replace("html","</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",j).getRegex()},Ee={...Y,html:g(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:"[^"]*"|\'[^\']*\'|\\\\s[^\'"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace("comment",K).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b").getRegex(),def:/^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +(["(][^\\n]+[")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:T,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:g(V).replace("hr",M).replace("heading",` *#{1,6} *[^\n]`).replace("lheading",ue).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Me=/^\\\\([!"#$%&\'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,Be=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ke=/^( {2,}|\\\\)\\n(?!\\s*$)/,qe=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,_=/[\\p{P}\\p{S}]/u,H=/[\\s\\p{P}\\p{S}]/u,ee=/[^\\s\\p{P}\\p{S}]/u,Ze=g(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,H).getRegex(),fe=/(?!~)[\\p{P}\\p{S}]/u,De=/(?!~)[\\s\\p{P}\\p{S}]/u,Qe=/(?:[^\\s\\p{P}\\p{S}]|~)/u,Ne=g(/link|precode-code|html/,"g").replace("link",/\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace("precode-",me?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),de=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,je=g(de,"u").replace(/punct/g,_).getRegex(),He=g(de,"u").replace(/punct/g,fe).getRegex(),xe="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)",Oe=g(xe,"gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Ge=g(xe,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,De).replace(/punct/g,fe).getRegex(),We=g("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Xe=g(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,_).getRegex(),Ue="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Fe=g(Ue,"gu").replace(/notPunctSpace/g,ee).replace(/punctSpace/g,H).replace(/punct/g,_).getRegex(),Ve=g(/\\\\(punct)/,"gu").replace(/punct/g,_).getRegex(),Je=g(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&\'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ke=g(K).replace("(?:-->|$)","-->").getRegex(),Ye=g("^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>").replace("comment",Ke).replace("attribute",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*"[^"]*"|\\s*=\\s*\'[^\']*\'|\\s*=\\s*[^\\s"\'=<>`]+)?/).getRegex(),D=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,et=g(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",D).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|\'(?:\\\\\'?|[^\'\\\\])*\'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),be=g(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",D).replace("ref",J).getRegex(),we=g(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",J).getRegex(),tt=g("reflink|nolink(?!\\\\()","g").replace("reflink",be).replace("nolink",we).getRegex(),se=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,te={_backpedal:T,anyPunctuation:Ve,autolink:Je,blockSkip:Ne,br:ke,code:Be,del:T,delLDelim:T,delRDelim:T,emStrongLDelim:je,emStrongRDelimAst:Oe,emStrongRDelimUnd:We,escape:Me,link:et,nolink:we,punctuation:Ze,reflink:be,reflinkSearch:tt,tag:Ye,text:qe,url:T},rt={...te,link:g(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",D).getRegex(),reflink:g(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",D).getRegex()},G={...te,emStrongRDelimAst:Ge,emStrongLDelim:He,delLDelim:Xe,delRDelim:Fe,url:g(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",se).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_\'"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_\'"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:g(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&\'*+\\/=?_`{\\|}~-]+@)))/).replace("protocol",se).getRegex()},nt={...G,br:g(ke).replace("{2,}","*").getRegex(),text:g(G.text).replace("\\\\b_","\\\\b_| {2,}\\\\n").replace(/\\{2,\\}/g,"*").getRegex()},Z={normal:Y,gfm:Ce,pedantic:Ee},C={normal:te,gfm:G,breaks:nt,pedantic:rt},st={"&":"&amp;","<":"&lt;",">":"&gt;",\'"\':"&quot;","\'":"&#39;"},ie=r=>st[r];function y(r,e){if(e){if(b.escapeTest.test(r))return r.replace(b.escapeReplace,ie)}else if(b.escapeTestNoEncode.test(r))return r.replace(b.escapeReplaceNoEncode,ie);return r}function le(r){try{r=encodeURI(r).replace(b.percentDecode,"%")}catch{return null}return r}function ae(r,e){let t=r.replace(b.findPipe,(i,a,l)=>{let o=!1,c=a;for(;--c>=0&&l[c]==="\\\\";)o=!o;return o?"|":" |"}),s=t.split(b.splitPipe),n=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),e)if(s.length>e)s.splice(e);else for(;s.length<e;)s.push("");for(;n<s.length;n++)s[n]=s[n].trim().replace(b.slashPipe,"|");return s}function S(r,e,t){let s=r.length;if(s===0)return"";let n=0;for(;n<s;){let i=r.charAt(s-n-1);if(i===e&&!t)n++;else if(i!==e&&t)n++;else break}return r.slice(0,s-n)}function oe(r){let e=r.split(`\n`),t=e.length-1;for(;t>=0&&b.blankLine.test(e[t]);)t--;return e.length-t<=2?r:e.slice(0,t+1).join(`\n`)}function it(r,e){if(r.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<r.length;s++)if(r[s]==="\\\\")s++;else if(r[s]===e[0])t++;else if(r[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function lt(r,e=0){let t=e,s="";for(let n of r)if(n===" "){let i=4-t%4;s+=" ".repeat(i),t+=i}else s+=n,t++;return s}function ce(r,e,t,s,n){let i=e.href,a=e.title||null,l=r[1].replace(n.other.outputLinkReplace,"$1");s.state.inLink=!0;let o={type:r[0].charAt(0)==="!"?"image":"link",raw:t,href:i,title:a,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,o}function at(r,e,t){let s=r.match(t.other.indentCodeCompensation);if(s===null)return e;let n=s[1];return e.split(`\n`).map(i=>{let a=i.match(t.other.beginningSpace);if(a===null)return i;let[l]=a;return l.length>=n.length?i.slice(n.length):i}).join(`\n`)}var Q=class{options;rules;lexer;constructor(r){this.options=r||A}space(r){let e=this.rules.block.newline.exec(r);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(r){let e=this.rules.block.code.exec(r);if(e){let t=this.options.pedantic?e[0]:oe(e[0]),s=t.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t,codeBlockStyle:"indented",text:s}}}fences(r){let e=this.rules.block.fences.exec(r);if(e){let t=e[0],s=at(t,e[3]||"",this.rules);return{type:"code",raw:t,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:s}}}heading(r){let e=this.rules.block.heading.exec(r);if(e){let t=e[2].trim();if(this.rules.other.endingHash.test(t)){let s=S(t,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(t=s.trim())}return{type:"heading",raw:S(e[0],`\n`),depth:e[1].length,text:t,tokens:this.lexer.inline(t)}}}hr(r){let e=this.rules.block.hr.exec(r);if(e)return{type:"hr",raw:S(e[0],`\n`)}}blockquote(r){let e=this.rules.block.blockquote.exec(r);if(e){let t=S(e[0],`\n`).split(`\n`),s="",n="",i=[];for(;t.length>0;){let a=!1,l=[],o;for(o=0;o<t.length;o++)if(this.rules.other.blockquoteStart.test(t[o]))l.push(t[o]),a=!0;else if(!a)l.push(t[o]);else break;t=t.slice(o);let c=l.join(`\n`),p=c.replace(this.rules.other.blockquoteSetextReplace,`\n $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}\n${c}`:c,n=n?`${n}\n${p}`:p;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=h,t.length===0)break;let u=i.at(-1);if(u?.type==="code")break;if(u?.type==="blockquote"){let x=u,f=x.raw+`\n`+t.join(`\n`),d=this.blockquote(f);i[i.length-1]=d,s=s.substring(0,s.length-x.raw.length)+d.raw,n=n.substring(0,n.length-x.text.length)+d.text;break}else if(u?.type==="list"){let x=u,f=x.raw+`\n`+t.join(`\n`),d=this.list(f);i[i.length-1]=d,s=s.substring(0,s.length-u.raw.length)+d.raw,n=n.substring(0,n.length-x.raw.length)+d.raw,t=f.substring(i.at(-1).raw.length).split(`\n`);continue}}return{type:"blockquote",raw:s,tokens:i,text:n}}}list(r){let e=this.rules.block.list.exec(r);if(e){let t=e[1].trim(),s=t.length>1,n={type:"list",raw:"",ordered:s,start:s?+t.slice(0,-1):"",loose:!1,items:[]};t=s?`\\\\d{1,9}\\\\${t.slice(-1)}`:`\\\\${t}`,this.options.pedantic&&(t=s?t:"[*+-]");let i=this.rules.other.listItemRegex(t),a=!1;for(;r;){let o=!1,c="",p="";if(!(e=i.exec(r))||this.rules.block.hr.test(r))break;c=e[0],r=r.substring(c.length);let h=lt(e[2].split(`\n`,1)[0],e[1].length),u=r.split(`\n`,1)[0],x=!h.trim(),f=0;if(this.options.pedantic?(f=2,p=h.trimStart()):x?f=e[1].length+1:(f=h.search(this.rules.other.nonSpaceChar),f=f>4?1:f,p=h.slice(f),f+=e[1].length),x&&this.rules.other.blankLine.test(u)&&(c+=u+`\n`,r=r.substring(u.length+1),o=!0),!o){let d=this.rules.other.nextBulletRegex(f),B=this.rules.other.hrRegex(f),$=this.rules.other.fencesBeginRegex(f),q=this.rules.other.headingBeginRegex(f),R=this.rules.other.htmlBeginRegex(f),v=this.rules.other.blockquoteBeginRegex(f);for(;r;){let O=r.split(`\n`,1)[0],I;if(u=O,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),I=u):I=u.replace(this.rules.other.tabCharGlobal," "),$.test(u)||q.test(u)||R.test(u)||v.test(u)||d.test(u)||B.test(u))break;if(I.search(this.rules.other.nonSpaceChar)>=f||!u.trim())p+=`\n`+I.slice(f);else{if(x||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||$.test(h)||q.test(h)||B.test(h))break;p+=`\n`+u}x=!u.trim(),c+=O+`\n`,r=r.substring(O.length+1),h=I.slice(f)}}n.loose||(a?n.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(a=!0)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),n.raw+=c}let l=n.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let o of n.items){this.lexer.state.top=!1,o.tokens=this.lexer.blockTokens(o.text,[]);let c=o.tokens[0];if(o.task&&(c?.type==="text"||c?.type==="paragraph")){o.text=o.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(o.raw);if(p){let h={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};o.checked=h.checked,n.loose?o.tokens[0]&&["paragraph","text"].includes(o.tokens[0].type)&&"tokens"in o.tokens[0]&&o.tokens[0].tokens?(o.tokens[0].raw=h.raw+o.tokens[0].raw,o.tokens[0].text=h.raw+o.tokens[0].text,o.tokens[0].tokens.unshift(h)):o.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):o.tokens.unshift(h)}}else o.task&&(o.task=!1);if(!n.loose){let p=o.tokens.filter(u=>u.type==="space"),h=p.length>0&&p.some(u=>this.rules.other.anyLine.test(u.raw));n.loose=h}}if(n.loose)for(let o of n.items){o.loose=!0;for(let c of o.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(r){let e=this.rules.block.html.exec(r);if(e){let t=oe(e[0]);return{type:"html",block:!0,raw:t,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:t}}}def(r){let e=this.rules.block.def.exec(r);if(e){let t=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:t,raw:S(e[0],`\n`),href:s,title:n}}}table(r){let e=this.rules.block.table.exec(r);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let t=ae(e[1]),s=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`\n`):[],i={type:"table",raw:S(e[0],`\n`),header:[],align:[],rows:[]};if(t.length===s.length){for(let a of s)this.rules.other.tableAlignRight.test(a)?i.align.push("right"):this.rules.other.tableAlignCenter.test(a)?i.align.push("center"):this.rules.other.tableAlignLeft.test(a)?i.align.push("left"):i.align.push(null);for(let a=0;a<t.length;a++)i.header.push({text:t[a],tokens:this.lexer.inline(t[a]),header:!0,align:i.align[a]});for(let a of n)i.rows.push(ae(a,i.header.length).map((l,o)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:i.align[o]})));return i}}lheading(r){let e=this.rules.block.lheading.exec(r);if(e){let t=e[1].trim();return{type:"heading",raw:S(e[0],`\n`),depth:e[2].charAt(0)==="="?1:2,text:t,tokens:this.lexer.inline(t)}}}paragraph(r){let e=this.rules.block.paragraph.exec(r);if(e){let t=e[1].charAt(e[1].length-1)===`\n`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:t,tokens:this.lexer.inline(t)}}}text(r){let e=this.rules.block.text.exec(r);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(r){let e=this.rules.inline.escape.exec(r);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(r){let e=this.rules.inline.tag.exec(r);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(r){let e=this.rules.inline.link.exec(r);if(e){let t=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(t)){if(!this.rules.other.endAngleBracket.test(t))return;let i=S(t.slice(0,-1),"\\\\");if((t.length-i.length)%2===0)return}else{let i=it(e[2],"()");if(i===-2)return;if(i>-1){let a=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,a).trim(),e[3]=""}}let s=e[2],n="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],n=i[3])}else n=e[3]?e[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(t)?s=s.slice(1):s=s.slice(1,-1)),ce(e,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(r,e){let t;if((t=this.rules.inline.reflink.exec(r))||(t=this.rules.inline.nolink.exec(r))){let s=(t[2]||t[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[s.toLowerCase()];if(!n){let i=t[0].charAt(0);return{type:"text",raw:i,text:i}}return ce(t,n,t[0],this.lexer,this.rules)}}emStrong(r,e,t=""){let s=this.rules.inline.emStrongLDelim.exec(r);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&t.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!t||this.rules.inline.punctuation.exec(t))){let n=[...s[0]].length-1,i,a,l=n,o=0,c=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*r.length+n);(s=c.exec(e))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(a=[...i].length,s[3]||s[4]){l+=a;continue}else if((s[5]||s[6])&&n%3&&!((n+a)%3)){o+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l+o);let p=[...s[0]][0].length,h=r.slice(0,n+s.index+p+a);if(Math.min(n,a)%2){let x=h.slice(1,-1);return{type:"em",raw:h,text:x,tokens:this.lexer.inlineTokens(x)}}let u=h.slice(2,-2);return{type:"strong",raw:h,text:u,tokens:this.lexer.inlineTokens(u)}}}}codespan(r){let e=this.rules.inline.code.exec(r);if(e){let t=e[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(t),n=this.rules.other.startingSpaceChar.test(t)&&this.rules.other.endingSpaceChar.test(t);return s&&n&&(t=t.substring(1,t.length-1)),{type:"codespan",raw:e[0],text:t}}}br(r){let e=this.rules.inline.br.exec(r);if(e)return{type:"br",raw:e[0]}}del(r,e,t=""){let s=this.rules.inline.delLDelim.exec(r);if(s&&(!s[1]||!t||this.rules.inline.punctuation.exec(t))){let n=[...s[0]].length-1,i,a,l=n,o=this.rules.inline.delRDelim;for(o.lastIndex=0,e=e.slice(-1*r.length+n);(s=o.exec(e))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(a=[...i].length,a!==n))continue;if(s[3]||s[4]){l+=a;continue}if(l-=a,l>0)continue;a=Math.min(a,a+l);let c=[...s[0]][0].length,p=r.slice(0,n+s.index+c+a),h=p.slice(n,-n);return{type:"del",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(r){let e=this.rules.inline.autolink.exec(r);if(e){let t,s;return e[2]==="@"?(t=e[1],s="mailto:"+t):(t=e[1],s=t),{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}url(r){let e;if(e=this.rules.inline.url.exec(r)){let t,s;if(e[2]==="@")t=e[0],s="mailto:"+t;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);t=e[0],e[1]==="www."?s="http://"+e[0]:s=e[0]}return{type:"link",raw:e[0],text:t,href:s,tokens:[{type:"text",raw:t,text:t}]}}}inlineText(r){let e=this.rules.inline.text.exec(r);if(e){let t=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:t}}}},w=class W{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||A,this.options.tokenizer=this.options.tokenizer||new Q,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:b,block:Z.normal,inline:C.normal};this.options.pedantic?(t.block=Z.pedantic,t.inline=C.pedantic):this.options.gfm&&(t.block=Z.gfm,this.options.breaks?t.inline=C.breaks:t.inline=C.gfm),this.tokenizer.rules=t}static get rules(){return{block:Z,inline:C}}static lex(e,t){return new W(t).lex(e)}static lexInline(e,t){return new W(t).inlineTokens(e)}lex(e){e=e.replace(b.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let s=this.inlineQueue[t];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(b.tabCharGlobal," ").replace(b.spaceLine,""));let n=1/0;for(;e;){if(e.length<n)n=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(l=>(i=l.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let l=t.at(-1);i.raw.length===1&&l!==void 0?l.raw+=`\n`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="paragraph"||l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.raw,this.inlineQueue.at(-1).src=l.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let l=1/0,o=e.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},o),typeof c=="number"&&c>=0&&(l=Math.min(l,c))}),l<1/0&&l>=0&&(a=e.substring(0,l+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let l=t.at(-1);s&&l?.type==="paragraph"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i),s=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let l=t.at(-1);l?.type==="text"?(l.raw+=(l.raw.endsWith(`\n`)?"":`\n`)+i.raw,l.text+=`\n`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=l.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let s=e;if(this.tokens.links){let l=Object.keys(this.tokens.links);l.length>0&&(s=s.replace(this.tokenizer.rules.inline.reflinkSearch,o=>l.includes(o.slice(o.lastIndexOf("[")+1,-1))?"["+"a".repeat(o.length-2)+"]":o))}s=s.replace(this.tokenizer.rules.inline.anyPunctuation,"++"),s=s.replace(this.tokenizer.rules.inline.blockSkip,(l,o,c)=>{let p=c?c.length:0;return l.slice(0,p)+"["+"a".repeat(l.length-p-2)+"]"}),s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,i="",a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}n||(i=""),n=!1;let l;if(this.options.extensions?.inline?.some(c=>(l=c.call({lexer:this},e,t))?(e=e.substring(l.raw.length),t.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let c=t.at(-1);l.type==="text"&&c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(l=this.tokenizer.emStrong(e,s,i)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.del(e,s,i)){e=e.substring(l.raw.length),t.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),t.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),t.push(l);continue}let o=e;if(this.options.extensions?.startInline){let c=1/0,p=e.slice(1),h;this.options.extensions.startInline.forEach(u=>{h=u.call({lexer:this},p),typeof h=="number"&&h>=0&&(c=Math.min(c,h))}),c<1/0&&c>=0&&(o=e.substring(0,c+1))}if(l=this.tokenizer.inlineText(o)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(i=l.raw.slice(-1)),n=!0;let c=t.at(-1);c?.type==="text"?(c.raw+=l.raw,c.text+=l.text):t.push(l);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},N=class{options;parser;constructor(r){this.options=r||A}space(r){return""}code({text:r,lang:e,escaped:t}){let s=(e||"").match(b.notSpaceStart)?.[0],n=r.replace(b.endingNewline,"")+`\n`;return s?\'<pre><code class="language-\'+y(s)+\'">\'+(t?n:y(n,!0))+`</code></pre>\n`:"<pre><code>"+(t?n:y(n,!0))+`</code></pre>\n`}blockquote({tokens:r}){return`<blockquote>\n${this.parser.parse(r)}</blockquote>\n`}html({text:r}){return r}def(r){return""}heading({tokens:r,depth:e}){return`<h${e}>${this.parser.parseInline(r)}</h${e}>\n`}hr(r){return`<hr>\n`}list(r){let e=r.ordered,t=r.start,s="";for(let a=0;a<r.items.length;a++){let l=r.items[a];s+=this.listitem(l)}let n=e?"ol":"ul",i=e&&t!==1?\' start="\'+t+\'"\':"";return"<"+n+i+`>\n`+s+"</"+n+`>\n`}listitem(r){return`<li>${this.parser.parse(r.tokens)}</li>\n`}checkbox({checked:r}){return"<input "+(r?\'checked="" \':"")+\'disabled="" type="checkbox"> \'}paragraph({tokens:r}){return`<p>${this.parser.parseInline(r)}</p>\n`}table(r){let e="",t="";for(let n=0;n<r.header.length;n++)t+=this.tablecell(r.header[n]);e+=this.tablerow({text:t});let s="";for(let n=0;n<r.rows.length;n++){let i=r.rows[n];t="";for(let a=0;a<i.length;a++)t+=this.tablecell(i[a]);s+=this.tablerow({text:t})}return s&&(s=`<tbody>${s}</tbody>`),`<table>\n<thead>\n`+e+`</thead>\n`+s+`</table>\n`}tablerow({text:r}){return`<tr>\n${r}</tr>\n`}tablecell(r){let e=this.parser.parseInline(r.tokens),t=r.header?"th":"td";return(r.align?`<${t} align="${r.align}">`:`<${t}>`)+e+`</${t}>\n`}strong({tokens:r}){return`<strong>${this.parser.parseInline(r)}</strong>`}em({tokens:r}){return`<em>${this.parser.parseInline(r)}</em>`}codespan({text:r}){return`<code>${y(r,!0)}</code>`}br(r){return"<br>"}del({tokens:r}){return`<del>${this.parser.parseInline(r)}</del>`}link({href:r,title:e,tokens:t}){let s=this.parser.parseInline(t),n=le(r);if(n===null)return s;r=n;let i=\'<a href="\'+r+\'"\';return e&&(i+=\' title="\'+y(e)+\'"\'),i+=">"+s+"</a>",i}image({href:r,title:e,text:t,tokens:s}){s&&(t=this.parser.parseInline(s,this.parser.textRenderer));let n=le(r);if(n===null)return y(t);r=n;let i=`<img src="${r}" alt="${y(t)}"`;return e&&(i+=` title="${y(e)}"`),i+=">",i}text(r){return"tokens"in r&&r.tokens?this.parser.parseInline(r.tokens):"escaped"in r&&r.escaped?r.text:y(r.text)}},re=class{strong({text:r}){return r}em({text:r}){return r}codespan({text:r}){return r}del({text:r}){return r}html({text:r}){return r}text({text:r}){return r}link({text:r}){return""+r}image({text:r}){return""+r}br(){return""}checkbox({raw:r}){return r}},m=class X{options;renderer;textRenderer;constructor(e){this.options=e||A,this.options.renderer=this.options.renderer||new N,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new re}static parse(e,t){return new X(t).parse(e)}static parseInline(e,t){return new X(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let s=0;s<e.length;s++){let n=e[s];if(this.options.extensions?.renderers?.[n.type]){let a=n,l=this.options.extensions.renderers[a.type].call({parser:this},a);if(l!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(a.type)){t+=l||"";continue}}let i=n;switch(i.type){case"space":{t+=this.renderer.space(i);break}case"hr":{t+=this.renderer.hr(i);break}case"heading":{t+=this.renderer.heading(i);break}case"code":{t+=this.renderer.code(i);break}case"table":{t+=this.renderer.table(i);break}case"blockquote":{t+=this.renderer.blockquote(i);break}case"list":{t+=this.renderer.list(i);break}case"checkbox":{t+=this.renderer.checkbox(i);break}case"html":{t+=this.renderer.html(i);break}case"def":{t+=this.renderer.def(i);break}case"paragraph":{t+=this.renderer.paragraph(i);break}case"text":{t+=this.renderer.text(i);break}default:{let a=\'Token with "\'+i.type+\'" type was not found.\';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let s="";for(let n=0;n<e.length;n++){let i=e[n];if(this.options.extensions?.renderers?.[i.type]){let l=this.options.extensions.renderers[i.type].call({parser:this},i);if(l!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){s+=l||"";continue}}let a=i;switch(a.type){case"escape":{s+=t.text(a);break}case"html":{s+=t.html(a);break}case"link":{s+=t.link(a);break}case"image":{s+=t.image(a);break}case"checkbox":{s+=t.checkbox(a);break}case"strong":{s+=t.strong(a);break}case"em":{s+=t.em(a);break}case"codespan":{s+=t.codespan(a);break}case"br":{s+=t.br(a);break}case"del":{s+=t.del(a);break}case"text":{s+=t.text(a);break}default:{let l=\'Token with "\'+a.type+\'" type was not found.\';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}},E=class{options;block;constructor(r){this.options=r||A}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(r){return r}postprocess(r){return r}processAllTokens(r){return r}emStrongMask(r){return r}provideLexer(r=this.block){return r?w.lex:w.lexInline}provideParser(r=this.block){return r?m.parse:m.parseInline}},ot=class{defaults=U();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=m;Renderer=N;TextRenderer=re;Lexer=w;Tokenizer=Q;Hooks=E;constructor(...r){this.use(...r)}walkTokens(r,e){let t=[];for(let s of r)switch(t=t.concat(e.call(this,s)),s.type){case"table":{let n=s;for(let i of n.header)t=t.concat(this.walkTokens(i.tokens,e));for(let i of n.rows)for(let a of i)t=t.concat(this.walkTokens(a.tokens,e));break}case"list":{let n=s;t=t.concat(this.walkTokens(n.items,e));break}default:{let n=s;this.defaults.extensions?.childTokens?.[n.type]?this.defaults.extensions.childTokens[n.type].forEach(i=>{let a=n[i].flat(1/0);t=t.concat(this.walkTokens(a,e))}):n.tokens&&(t=t.concat(this.walkTokens(n.tokens,e)))}}return t}use(...r){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return r.forEach(t=>{let s={...t};if(s.async=this.defaults.async||s.async||!1,t.extensions&&(t.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let i=e.renderers[n.name];i?e.renderers[n.name]=function(...a){let l=n.renderer.apply(this,a);return l===!1&&(l=i.apply(this,a)),l}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be \'block\' or \'inline\'");let i=e[n.level];i?i.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),s.extensions=e),t.renderer){let n=this.defaults.renderer||new N(this.defaults);for(let i in t.renderer){if(!(i in n))throw new Error(`renderer \'${i}\' does not exist`);if(["options","parser"].includes(i))continue;let a=i,l=t.renderer[a],o=n[a];n[a]=(...c)=>{let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p||""}}s.renderer=n}if(t.tokenizer){let n=this.defaults.tokenizer||new Q(this.defaults);for(let i in t.tokenizer){if(!(i in n))throw new Error(`tokenizer \'${i}\' does not exist`);if(["options","rules","lexer"].includes(i))continue;let a=i,l=t.tokenizer[a],o=n[a];n[a]=(...c)=>{let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p}}s.tokenizer=n}if(t.hooks){let n=this.defaults.hooks||new E;for(let i in t.hooks){if(!(i in n))throw new Error(`hook \'${i}\' does not exist`);if(["options","block"].includes(i))continue;let a=i,l=t.hooks[a],o=n[a];E.passThroughHooks.has(i)?n[a]=c=>{if(this.defaults.async&&E.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await l.call(n,c);return o.call(n,h)})();let p=l.call(n,c);return o.call(n,p)}:n[a]=(...c)=>{if(this.defaults.async)return(async()=>{let h=await l.apply(n,c);return h===!1&&(h=await o.apply(n,c)),h})();let p=l.apply(n,c);return p===!1&&(p=o.apply(n,c)),p}}s.hooks=n}if(t.walkTokens){let n=this.defaults.walkTokens,i=t.walkTokens;s.walkTokens=function(a){let l=[];return l.push(i.call(this,a)),n&&(l=l.concat(n.call(this,a))),l}}this.defaults={...this.defaults,...s}}),this}setOptions(r){return this.defaults={...this.defaults,...r},this}lexer(r,e){return w.lex(r,e??this.defaults)}parser(r,e){return m.parse(r,e??this.defaults)}parseMarkdown(r){return(e,t)=>{let s={...t},n={...this.defaults,...s},i=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&s.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(n.hooks&&(n.hooks.options=n,n.hooks.block=r),n.async)return(async()=>{let a=n.hooks?await n.hooks.preprocess(e):e,l=await(n.hooks?await n.hooks.provideLexer(r):r?w.lex:w.lexInline)(a,n),o=n.hooks?await n.hooks.processAllTokens(l):l;n.walkTokens&&await Promise.all(this.walkTokens(o,n.walkTokens));let c=await(n.hooks?await n.hooks.provideParser(r):r?m.parse:m.parseInline)(o,n);return n.hooks?await n.hooks.postprocess(c):c})().catch(i);try{n.hooks&&(e=n.hooks.preprocess(e));let a=(n.hooks?n.hooks.provideLexer(r):r?w.lex:w.lexInline)(e,n);n.hooks&&(a=n.hooks.processAllTokens(a)),n.walkTokens&&this.walkTokens(a,n.walkTokens);let l=(n.hooks?n.hooks.provideParser(r):r?m.parse:m.parseInline)(a,n);return n.hooks&&(l=n.hooks.postprocess(l)),l}catch(a){return i(a)}}}onError(r,e){return t=>{if(t.message+=`\nPlease report this to https://github.com/markedjs/marked.`,r){let s="<p>An error occurred:</p><pre>"+y(t.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(t);throw t}}},z=new ot;function k(r,e){return z.parse(r,e)}k.options=k.setOptions=function(r){return z.setOptions(r),k.defaults=z.defaults,he(k.defaults),k};k.getDefaults=U;k.defaults=A;k.use=function(...r){return z.use(...r),k.defaults=z.defaults,he(k.defaults),k};k.walkTokens=function(r,e){return z.walkTokens(r,e)};k.parseInline=z.parseInline;k.Parser=m;k.parser=m.parse;k.Renderer=N;k.TextRenderer=re;k.Lexer=w;k.lexer=w.lex;k.Tokenizer=Q;k.Hooks=E;k.parse=k;var ut=k.options,gt=k.setOptions,kt=k.use,ft=k.walkTokens,dt=k.parseInline;var xt=m.parse,bt=w.lex;var ct=0;function ht(r){if(typeof r!="string"||typeof performance.mark!="function"||typeof performance.measure!="function")return null;let e=ct++,t={name:r,startMark:`${r}:start:${e}`,endMark:`${r}:end:${e}`};try{return performance.mark(t.startMark),t}catch{return null}}function pt(r){if(r)try{performance.mark(r.endMark),performance.measure(r.name,r.startMark,r.endMark)}catch{}finally{try{performance.clearMarks?.(r.startMark),performance.clearMarks?.(r.endMark)}catch{}}}k.use({extensions:[{name:"blockMath",level:"block",start(r){return r.match(/^ {0,3}\\$\\$/m)?.index},tokenizer(r){let e=/^ {0,3}\\$\\$([\\s\\S]+?)\\$\\$[ \\t]*(?:\\n|$)/.exec(r);if(e)return{type:"blockMath",raw:e[0],text:e[1].trim()}},renderer(r){return r.raw}},{name:"inlineMath",level:"inline",start(r){return r.match(/(?<![\\\\$])\\$(?![$\\s])/)?.index},tokenizer(r){let e=/^\\$(?![$\\s\\d])((?:\\\\\\$|[^$\\n])*?)(?<!\\s)\\$(?!\\d)/.exec(r);if(e)return{type:"inlineMath",raw:e[0],text:e[1].trim()}},renderer(r){return r.raw}}]});var P=new Map;self.onmessage=r=>{let e=r.data;if(typeof e!="object"||e===null)return;let{id:t,text:s,append:n,expectedLength:i,oldRaws:a,instance:l,baseVersion:o,dispose:c,userTimingName:p}=e;if(c===!0){typeof l=="string"&&P.delete(l);return}let h=typeof l=="string"?l:null,u=typeof o=="number"?o:null,x,f=null;if(typeof n=="string"){if(h===null||u===null){self.postMessage({id:t,needResync:!0});return}let d=P.get(h);if(!d||d.version!==u){self.postMessage({id:t,needResync:!0});return}if(x=d.source+n,typeof i=="number"&&x.length!==i){P.delete(h),self.postMessage({id:t,needResync:!0});return}f=d.raws}else if(typeof s=="string"){if(x=s,Array.isArray(a))f=a;else if(h!==null&&u!==null){let d=P.get(h);if(d&&d.version===u)f=d.raws;else{self.postMessage({id:t,needResync:!0});return}}}else return;try{let d=typeof p=="string"?ht(p):null,B=performance.now(),$;try{$=k.lexer(x)}finally{d&&pt(d)}let q=performance.now()-B,R=0;if(f){let v=Math.min(f.length,$.length);for(;R<v&&f[R]===$[R].raw;R++);}h!==null&&u!==null&&P.set(h,{version:u+1,raws:$.map(v=>v.raw),source:x}),self.postMessage({id:t,matchLen:R,tail:$.slice(R),lexerMs:q,sourceCharsLexed:x.length})}catch(d){h!==null&&P.delete(h),self.postMessage({id:t,error:String(d)})}};})();\n';
428
460
 
429
461
  // src/Markdown.ts
430
462
  var now = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
@@ -439,6 +471,27 @@ function lexMarkdown(text, userTiming) {
439
471
  }
440
472
  import_marked.marked.use({
441
473
  extensions: [
474
+ {
475
+ name: "blockMath",
476
+ level: "block",
477
+ start(src) {
478
+ return src.match(/^ {0,3}\$\$/m)?.index;
479
+ },
480
+ tokenizer(src) {
481
+ const match = /^ {0,3}\$\$([\s\S]+?)\$\$[ \t]*(?:\n|$)/.exec(src);
482
+ if (match) {
483
+ return {
484
+ type: "blockMath",
485
+ raw: match[0],
486
+ text: match[1].trim()
487
+ };
488
+ }
489
+ return void 0;
490
+ },
491
+ renderer(token) {
492
+ return token.raw;
493
+ }
494
+ },
442
495
  {
443
496
  name: "inlineMath",
444
497
  level: "inline",
@@ -462,23 +515,191 @@ import_marked.marked.use({
462
515
  }
463
516
  ]
464
517
  });
465
- var adaptor = (0, import_liteAdaptor.liteAdaptor)();
466
- (0, import_html.RegisterHTMLHandler)(adaptor);
467
- var tex = new import_tex.TeX({ packages: import_AllPackages.AllPackages });
468
- var svg = new import_svg.SVG({ fontCache: "local" });
469
- var htmlMathJax = import_mathjax.mathjax.document("", { InputJax: tex, OutputJax: svg });
470
- function renderMathToSVGDataURI(formula, displayMode) {
518
+ var mathConverter = null;
519
+ var mathLoad = null;
520
+ function interop(mod, key) {
521
+ const ns = mod;
522
+ if (typeof ns?.[key] !== "undefined") return ns;
523
+ const fallback = ns?.default;
524
+ if (fallback && typeof fallback[key] !== "undefined") return fallback;
525
+ throw new Error(`mathjax-full module is missing export "${key}"`);
526
+ }
527
+ function preloadMathJax() {
528
+ if (mathLoad) return mathLoad;
529
+ mathLoad = (async () => {
530
+ const [mathjaxMod, texMod, svgMod, adaptorMod, handlerMod, packagesMod] = await Promise.all([
531
+ import("mathjax-full/js/mathjax.js"),
532
+ import("mathjax-full/js/input/tex.js"),
533
+ import("mathjax-full/js/output/svg.js"),
534
+ import("mathjax-full/js/adaptors/liteAdaptor.js"),
535
+ import("mathjax-full/js/handlers/html.js"),
536
+ import("mathjax-full/js/input/tex/AllPackages.js")
537
+ ]);
538
+ const { mathjax } = interop(mathjaxMod, "mathjax");
539
+ const { TeX } = interop(texMod, "TeX");
540
+ const { SVG } = interop(svgMod, "SVG");
541
+ const { liteAdaptor } = interop(adaptorMod, "liteAdaptor");
542
+ const { RegisterHTMLHandler } = interop(handlerMod, "RegisterHTMLHandler");
543
+ const { AllPackages } = interop(packagesMod, "AllPackages");
544
+ const adaptor = liteAdaptor();
545
+ RegisterHTMLHandler(adaptor);
546
+ const tex = new TeX({ packages: AllPackages });
547
+ const svg = new SVG({ fontCache: "local" });
548
+ const htmlMathJax = mathjax.document("", { InputJax: tex, OutputJax: svg });
549
+ mathConverter = (formula, displayMode, color) => convertMathToSVGDataURI(
550
+ formula,
551
+ displayMode,
552
+ (f, d) => adaptor.innerHTML(htmlMathJax.convert(f, { display: d })),
553
+ color
554
+ );
555
+ })().catch((e) => {
556
+ console.error("MathJax failed to load; formulas will render as TeX source", e);
557
+ });
558
+ return mathLoad;
559
+ }
560
+ function isMathJaxReady() {
561
+ return mathConverter !== null;
562
+ }
563
+ var EX_PER_EM = 0.4421;
564
+ function exToPx(ex, fontSize) {
565
+ return ex * fontSize * EX_PER_EM;
566
+ }
567
+ function fontSizeFromFont(font) {
568
+ const pxIndex = font.indexOf("px");
569
+ if (pxIndex <= 0) return void 0;
570
+ let start = pxIndex;
571
+ while (start > 0) {
572
+ const ch = font[start - 1];
573
+ if (ch >= "0" && ch <= "9" || ch === ".") start--;
574
+ else break;
575
+ }
576
+ if (start === pxIndex) return void 0;
577
+ const size = parseFloat(font.slice(start, pxIndex));
578
+ return Number.isFinite(size) ? size : void 0;
579
+ }
580
+ var mathCache = /* @__PURE__ */ new Map();
581
+ var MATH_CACHE_LIMIT = 256;
582
+ var inlineMathRasters = /* @__PURE__ */ new Map();
583
+ var inlineMathRasterWaiters = /* @__PURE__ */ new Set();
584
+ function ensureInlineMathRaster(uri) {
585
+ const existing = inlineMathRasters.get(uri);
586
+ if (existing) return existing;
587
+ const entry = { decoded: false };
588
+ inlineMathRasters.set(uri, entry);
589
+ if (typeof globalThis.Image !== "undefined") {
590
+ const bitmap = new globalThis.Image();
591
+ bitmap.onload = () => {
592
+ entry.decoded = true;
593
+ for (const notify of inlineMathRasterWaiters) notify();
594
+ };
595
+ bitmap.src = uri;
596
+ entry.bitmap = bitmap;
597
+ }
598
+ return entry;
599
+ }
600
+ function paintInlineMath(uri, surface, box) {
601
+ const raster = ensureInlineMathRaster(uri);
602
+ if (!raster.decoded || !raster.bitmap) return;
603
+ surface.drawImage(raster.bitmap, box.x, box.y, box.width, box.height);
604
+ }
605
+ var MATH_LANGS = /* @__PURE__ */ new Set(["math", "latex", "tex"]);
606
+ function containsInlineMath(token) {
607
+ if (token.type === "inlineMath") return true;
608
+ const anyToken = token;
609
+ if (Array.isArray(anyToken.tokens) && anyToken.tokens.some(containsInlineMath)) {
610
+ return true;
611
+ }
612
+ if (Array.isArray(anyToken.items) && anyToken.items.some(containsInlineMath)) {
613
+ return true;
614
+ }
615
+ if (Array.isArray(anyToken.header) && anyToken.header.some(containsInlineMath)) {
616
+ return true;
617
+ }
618
+ if (Array.isArray(anyToken.rows)) {
619
+ for (const row of anyToken.rows) {
620
+ if (Array.isArray(row) && row.some(containsInlineMath)) return true;
621
+ }
622
+ }
623
+ return false;
624
+ }
625
+ var FENCE_OPEN_RE = /^ {0,3}(`{3,}|~{3,})/;
626
+ var FENCE_CLOSE_RE = /^ {0,3}(`+|~+)[ \t]*$/;
627
+ function isFenceClosed(raw) {
628
+ const lines = raw.split("\n");
629
+ const open = FENCE_OPEN_RE.exec(lines[0]);
630
+ if (!open) return false;
631
+ const marker = open[1][0];
632
+ const minLen = open[1].length;
633
+ for (let i = 1; i < lines.length; i++) {
634
+ const close = FENCE_CLOSE_RE.exec(lines[i]);
635
+ if (close && close[1][0] === marker && close[1].length >= minLen) return true;
636
+ }
637
+ return false;
638
+ }
639
+ function paragraphHasImage(token) {
640
+ return token.tokens?.some((child) => child.type === "image") === true;
641
+ }
642
+ function lastIndexOfImage(tokens) {
643
+ for (let i = tokens.length - 1; i >= 0; i--) {
644
+ if (tokens[i].type === "image") return i;
645
+ }
646
+ return -1;
647
+ }
648
+ function expectedImageParagraphChildren(tokens) {
649
+ let children = 0;
650
+ let inTextRun = false;
651
+ for (const token of tokens) {
652
+ if (token.type === "image") {
653
+ children++;
654
+ inTextRun = false;
655
+ } else if (!inTextRun) {
656
+ children++;
657
+ inTextRun = true;
658
+ }
659
+ }
660
+ return children;
661
+ }
662
+ function rendersAsMath(token) {
663
+ return MATH_LANGS.has((token.lang ?? "").toLowerCase()) && token.text.trim() !== "" && isFenceClosed(token.raw);
664
+ }
665
+ function renderMathToSVGDataURI(formula, displayMode, color) {
666
+ const key = `${displayMode ? 1 : 0}\0${color}\0${formula}`;
667
+ const hit = mathCache.get(key);
668
+ if (hit) return hit;
669
+ if (!mathConverter) return null;
670
+ const converted = mathConverter(formula, displayMode, color);
671
+ if (converted) {
672
+ if (mathCache.size >= MATH_CACHE_LIMIT) {
673
+ const oldest = mathCache.keys().next().value;
674
+ if (oldest !== void 0) mathCache.delete(oldest);
675
+ }
676
+ mathCache.set(key, converted);
677
+ }
678
+ return converted;
679
+ }
680
+ function applyMathColor(svg, color) {
681
+ const openTag = svg.match(/<svg\b[^>]*>/);
682
+ if (!openTag) return svg;
683
+ const tag = openTag[0];
684
+ const colored = /\bstyle="/.test(tag) ? tag.replace(/\bstyle="/, `style="color:${color};`) : tag.replace(/^<svg\b/, `<svg style="color:${color}"`);
685
+ return svg.replace(tag, colored);
686
+ }
687
+ function convertMathToSVGDataURI(formula, displayMode, typeset, color) {
471
688
  try {
472
- const node = htmlMathJax.convert(formula, { display: displayMode });
473
- const svgString = adaptor.innerHTML(node);
689
+ const svgString = applyMathColor(typeset(formula, displayMode), color);
474
690
  const wMatch = svgString.match(/width="([^"]+)ex"/);
475
691
  const hMatch = svgString.match(/height="([^"]+)ex"/);
476
692
  const wEx = wMatch ? parseFloat(wMatch[1]) : 10;
477
693
  const hEx = hMatch ? parseFloat(hMatch[1]) : 2;
478
- const width = wEx * 8;
479
- const height = hEx * 8;
694
+ const vMatch = svgString.match(/vertical-align:\s*(-?[\d.]+)ex/);
695
+ const depthEx = vMatch ? Math.max(0, -parseFloat(vMatch[1])) : 0;
480
696
  const base64 = btoa(unescape(encodeURIComponent(svgString)));
481
- return { uri: `data:image/svg+xml;base64,${base64}`, width, height };
697
+ return {
698
+ uri: `data:image/svg+xml;base64,${base64}`,
699
+ widthEx: wEx,
700
+ heightEx: hEx,
701
+ depthEx
702
+ };
482
703
  } catch (e) {
483
704
  console.error("MathJax error", e);
484
705
  return null;
@@ -493,6 +714,7 @@ function runSyncFallback(entry) {
493
714
  entry.cb(0, lexMarkdown(entry.text, entry.userTiming), true);
494
715
  } catch (err) {
495
716
  console.warn("Markdown sync fallback parse failed", err);
717
+ entry.onDropped?.();
496
718
  }
497
719
  }
498
720
  if (typeof Worker !== "undefined") {
@@ -1018,13 +1240,13 @@ function codeAtlas() {
1018
1240
  function decodeEntities(text) {
1019
1241
  return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
1020
1242
  }
1021
- function collectSpans(tokens, inherited, theme, out) {
1243
+ function collectSpans(tokens, inherited, theme, out, blockFontSize) {
1022
1244
  for (const token of tokens) {
1023
1245
  switch (token.type) {
1024
1246
  case "strong": {
1025
1247
  const t = token;
1026
1248
  if (t.tokens) {
1027
- collectSpans(t.tokens, { ...inherited, bold: true }, theme, out);
1249
+ collectSpans(t.tokens, { ...inherited, bold: true }, theme, out, blockFontSize);
1028
1250
  } else {
1029
1251
  out.push({
1030
1252
  text: decodeEntities(t.text),
@@ -1036,7 +1258,7 @@ function collectSpans(tokens, inherited, theme, out) {
1036
1258
  case "em": {
1037
1259
  const t = token;
1038
1260
  if (t.tokens) {
1039
- collectSpans(t.tokens, { ...inherited, italic: true }, theme, out);
1261
+ collectSpans(t.tokens, { ...inherited, italic: true }, theme, out, blockFontSize);
1040
1262
  } else {
1041
1263
  out.push({
1042
1264
  text: decodeEntities(t.text),
@@ -1072,10 +1294,32 @@ function collectSpans(tokens, inherited, theme, out) {
1072
1294
  }
1073
1295
  case "inlineMath": {
1074
1296
  const t = token;
1075
- out.push({
1076
- text: decodeEntities(t.raw),
1077
- style: { ...inherited, color: "#fcd34d" }
1078
- });
1297
+ const runSize = inherited.fontSize ?? blockFontSize ?? theme.fontSize;
1298
+ const runColor = inherited.color ?? theme.textColor;
1299
+ const rendered = renderMathToSVGDataURI(t.text, false, runColor);
1300
+ if (rendered) {
1301
+ const uri = rendered.uri;
1302
+ out.push({
1303
+ text: import_core.OBJECT_REPLACEMENT,
1304
+ style: inherited,
1305
+ object: {
1306
+ width: exToPx(rendered.widthEx, runSize),
1307
+ height: exToPx(rendered.heightEx, runSize),
1308
+ depth: exToPx(rendered.depthEx, runSize),
1309
+ // The TeX source is the accessible name: without it a screen reader
1310
+ // receives only the invisible U+FFFC sentinel.
1311
+ alt: t.text,
1312
+ // Without this the box is reserved and stays empty. The engine does
1313
+ // not draw objects, and nothing else in the tree holds the raster.
1314
+ paint: (surface, box) => paintInlineMath(uri, surface, box)
1315
+ }
1316
+ });
1317
+ } else {
1318
+ out.push({
1319
+ text: decodeEntities(t.raw),
1320
+ style: { ...inherited, color: "#fcd34d" }
1321
+ });
1322
+ }
1079
1323
  break;
1080
1324
  }
1081
1325
  case "link": {
@@ -1086,7 +1330,7 @@ function collectSpans(tokens, inherited, theme, out) {
1086
1330
  color: "#38bdf8"
1087
1331
  };
1088
1332
  if (t.tokens && t.tokens.length > 0) {
1089
- collectSpans(t.tokens, linkStyle, theme, out);
1333
+ collectSpans(t.tokens, linkStyle, theme, out, blockFontSize);
1090
1334
  } else {
1091
1335
  out.push({ text: decodeEntities(t.text), style: linkStyle });
1092
1336
  }
@@ -1095,7 +1339,7 @@ function collectSpans(tokens, inherited, theme, out) {
1095
1339
  case "text": {
1096
1340
  const t = token;
1097
1341
  if ("tokens" in t && t.tokens?.length) {
1098
- collectSpans(t.tokens, inherited, theme, out);
1342
+ collectSpans(t.tokens, inherited, theme, out, blockFontSize);
1099
1343
  } else {
1100
1344
  const decoded = decodeEntities(t.text);
1101
1345
  if (decoded) {
@@ -1118,10 +1362,37 @@ function collectSpans(tokens, inherited, theme, out) {
1118
1362
  }
1119
1363
  }
1120
1364
  }
1365
+ function findUnclosedInline(text) {
1366
+ let best = null;
1367
+ const tick = text.lastIndexOf("`");
1368
+ if (tick !== -1 && tick < text.length - 1) {
1369
+ return { kind: "codespan", at: tick, contentAt: tick + 1 };
1370
+ }
1371
+ if (tick !== -1) return null;
1372
+ const emphasis = /(\*{1,2}(?!\*)|_{1,2}(?!_))(?=[^\s])/g;
1373
+ for (let match = emphasis.exec(text); match !== null; match = emphasis.exec(text)) {
1374
+ const marker = match[1];
1375
+ const at = match.index;
1376
+ if (marker[0] === "_" && at > 0 && /[\w]/.test(text[at - 1])) continue;
1377
+ best = {
1378
+ kind: marker.length === 2 ? "strong" : "em",
1379
+ at,
1380
+ contentAt: at + marker.length
1381
+ };
1382
+ }
1383
+ const bracket = text.lastIndexOf("[");
1384
+ if (bracket !== -1 && bracket < text.length - 1 && (best === null || bracket > best.at)) {
1385
+ const closed = /\]\([^)]*\)/.test(text.slice(bracket));
1386
+ if (!closed) {
1387
+ best = { kind: "link", at: bracket, contentAt: bracket + 1 };
1388
+ }
1389
+ }
1390
+ return best;
1391
+ }
1121
1392
  function renderInlineToRichText(tokens, fallbackText, font, color, maxWidth, theme, selectable, onLinkClick) {
1122
1393
  const spans = [];
1123
1394
  if (tokens && tokens.length > 0) {
1124
- collectSpans(tokens, {}, theme, spans);
1395
+ collectSpans(tokens, {}, theme, spans, fontSizeFromFont(font));
1125
1396
  }
1126
1397
  if (spans.length === 0) {
1127
1398
  spans.push({ text: decodeEntities(fallbackText) });
@@ -1153,6 +1424,51 @@ var Markdown = class extends import_ui.UIComponent {
1153
1424
  onLayoutUpdated;
1154
1425
  rawMarkdown;
1155
1426
  streamController = null;
1427
+ /**
1428
+ * Trailing-unclosed-syntax policy of the active stream, or `'literal'` when no
1429
+ * stream is open.
1430
+ *
1431
+ * Held here rather than read back off the controller because it is a rendering
1432
+ * concern: `StreamController` owns buffering and pacing and has no view of the
1433
+ * entity tree, while the guess is a transform applied where spans are built.
1434
+ */
1435
+ streamIncompleteMode = "literal";
1436
+ /** End-of-stream callback of the active stream, if it supplied one. */
1437
+ streamOnStable = null;
1438
+ /**
1439
+ * The trailing paragraph entity currently showing an optimistic guess, plus the
1440
+ * token it was rendered from.
1441
+ *
1442
+ * Both halves are needed. The entity is what must be re-rendered to drop the
1443
+ * guess; the token is what it must be re-rendered FROM, and it is the only
1444
+ * copy — `this.tokens` has already moved on by the time an unwind is decided.
1445
+ * `null` means no guess is live, which is the state every `'literal'` stream
1446
+ * and every closed stream stays in.
1447
+ */
1448
+ optimisticTail = null;
1449
+ /** Resolvers waiting for every in-flight worker append to have been applied. */
1450
+ appendSettledWaiters = [];
1451
+ /** True only inside an `onStable` callback, to reject reentrant mutation. */
1452
+ inStableCallback = false;
1453
+ /** Set by {@link destroy} so late settlement work skips a torn-down tree. */
1454
+ isDestroyed = false;
1455
+ /**
1456
+ * This instance's entry in {@link inlineMathRasterWaiters}, or `undefined` if it
1457
+ * has never rendered inline math.
1458
+ *
1459
+ * Subscribed lazily so a document without formulas costs nothing, and held as a
1460
+ * field only so {@link destroy} can remove the exact closure it added.
1461
+ */
1462
+ inlineMathRepaint;
1463
+ /**
1464
+ * True while this document is waiting on the lazy MathJax load.
1465
+ *
1466
+ * Tracked per instance rather than read off the module state because it also
1467
+ * gates settlement: `await close()` and `onStable` must not resolve while a
1468
+ * formula is still showing TeX source, or a caller doing expensive one-time
1469
+ * work on a "final" document would measure and export placeholder boxes.
1470
+ */
1471
+ mathLoadPending = false;
1156
1472
  _userTiming;
1157
1473
  tokens = [];
1158
1474
  // At most one worker lex request in flight at a time. Required for the
@@ -1310,21 +1626,44 @@ var Markdown = class extends import_ui.UIComponent {
1310
1626
  {
1311
1627
  append: (chunk) => this.appendMarkdownCore(chunk),
1312
1628
  release: (released) => {
1313
- if (this.streamController === released) this.streamController = null;
1629
+ if (this.streamController !== released) return;
1630
+ this.streamController = null;
1631
+ this.streamIncompleteMode = "literal";
1632
+ this.streamOnStable = null;
1633
+ this.unwindOptimisticTail();
1634
+ },
1635
+ onClose: async () => {
1636
+ await this.waitForAppendSettled();
1637
+ if (this.isDestroyed) return;
1638
+ this.unwindOptimisticTail();
1639
+ const onStable = this.streamOnStable;
1640
+ if (!onStable) return;
1641
+ this.inStableCallback = true;
1642
+ try {
1643
+ onStable(Array.from(this.content.children));
1644
+ } finally {
1645
+ this.inStableCallback = false;
1646
+ }
1314
1647
  }
1315
1648
  },
1316
1649
  options
1317
1650
  );
1318
- if (controller.state === "open") this.streamController = controller;
1651
+ if (controller.state === "open") {
1652
+ this.streamController = controller;
1653
+ this.streamIncompleteMode = options.incompleteMode ?? "literal";
1654
+ this.streamOnStable = options.onStable ?? null;
1655
+ }
1319
1656
  return controller;
1320
1657
  }
1321
1658
  /** Replace all markdown content (full rebuild). */
1322
1659
  setContent(markdown) {
1660
+ this.assertNotInStableCallback("setContent");
1323
1661
  this.streamController?.abort(new Error("Markdown content was replaced"));
1324
1662
  for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
1325
1663
  this.pendingWorkerIds.clear();
1326
1664
  this.appendInFlight = false;
1327
1665
  this.appendPending = false;
1666
+ this.flushAppendSettledWaiters();
1328
1667
  this.rawMarkdown = markdown;
1329
1668
  this.workerSourceLen = 0;
1330
1669
  while (this.content.children.length > 0) {
@@ -1340,12 +1679,35 @@ var Markdown = class extends import_ui.UIComponent {
1340
1679
  * the whole subtree alive until the worker replied), then recurse into the
1341
1680
  * content subtree via `super.destroy()` so every block's resources are freed.
1342
1681
  */
1682
+ /**
1683
+ * Repaint this document when an inline formula's raster finishes decoding.
1684
+ *
1685
+ * Idempotent — called on every render of a math-bearing token, and the set holds
1686
+ * one closure per instance.
1687
+ */
1688
+ subscribeInlineMathRepaint() {
1689
+ if (this.inlineMathRepaint || this.isDestroyed) return;
1690
+ const repaint = () => {
1691
+ if (this.isDestroyed) return;
1692
+ this.scene?.markDirty();
1693
+ };
1694
+ this.inlineMathRepaint = repaint;
1695
+ inlineMathRasterWaiters.add(repaint);
1696
+ }
1343
1697
  destroy() {
1698
+ this.isDestroyed = true;
1699
+ this.optimisticTail = null;
1344
1700
  this.streamController?.destroy();
1345
1701
  for (const id of this.pendingWorkerIds) workerCallbacks.delete(id);
1346
1702
  this.pendingWorkerIds.clear();
1347
1703
  this.appendInFlight = false;
1348
1704
  this.appendPending = false;
1705
+ this.mathLoadPending = false;
1706
+ this.flushAppendSettledWaiters();
1707
+ if (this.inlineMathRepaint) {
1708
+ inlineMathRasterWaiters.delete(this.inlineMathRepaint);
1709
+ this.inlineMathRepaint = void 0;
1710
+ }
1349
1711
  markdownWorker?.postMessage({
1350
1712
  instance: this.workerInstanceId,
1351
1713
  dispose: true
@@ -1534,6 +1896,7 @@ var Markdown = class extends import_ui.UIComponent {
1534
1896
  }
1535
1897
  /** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
1536
1898
  appendMarkdown(chunk) {
1899
+ this.assertNotInStableCallback("appendMarkdown");
1537
1900
  this.streamController?.flush();
1538
1901
  return this.appendMarkdownCore(chunk);
1539
1902
  }
@@ -1602,6 +1965,7 @@ var Markdown = class extends import_ui.UIComponent {
1602
1965
  this.appendPending = false;
1603
1966
  this.dispatchAppend();
1604
1967
  }
1968
+ this.flushAppendSettledWaiters();
1605
1969
  },
1606
1970
  // The worker can't trust what it holds for this request; retry it once with
1607
1971
  // the full text and raws attached. `this.tokens` is untouched (no
@@ -1612,6 +1976,20 @@ var Markdown = class extends import_ui.UIComponent {
1612
1976
  this.workerSourceLen = 0;
1613
1977
  this.dispatchAppend(true);
1614
1978
  },
1979
+ // Neither the worker nor the fallback lexer could produce tokens for this
1980
+ // request, so `this.tokens` stays as it was. Only the in-flight bookkeeping
1981
+ // needs unwinding — including any coalesced chunk waiting behind it, which
1982
+ // still has to be attempted.
1983
+ onDropped: () => {
1984
+ this.pendingWorkerIds.delete(id);
1985
+ this.appendInFlight = false;
1986
+ this.workerSourceLen = 0;
1987
+ if (this.appendPending) {
1988
+ this.appendPending = false;
1989
+ this.dispatchAppend(true);
1990
+ }
1991
+ this.flushAppendSettledWaiters();
1992
+ },
1615
1993
  text: this.rawMarkdown,
1616
1994
  userTiming: this._userTiming
1617
1995
  });
@@ -1633,6 +2011,647 @@ var Markdown = class extends import_ui.UIComponent {
1633
2011
  }
1634
2012
  });
1635
2013
  }
2014
+ /**
2015
+ * Spans for one paragraph token exactly as `marked` produced it.
2016
+ *
2017
+ * The literal baseline: what every release renders, and what an optimistic
2018
+ * guess is unwound back to.
2019
+ */
2020
+ literalParagraphSpans(token) {
2021
+ const spans = [];
2022
+ if (token.tokens && token.tokens.length > 0) {
2023
+ collectSpans(token.tokens, {}, this.theme, spans);
2024
+ }
2025
+ if (spans.length === 0) spans.push({ text: token.text });
2026
+ return spans;
2027
+ }
2028
+ /**
2029
+ * Update a reused blockquote's tail child in place, or report that it cannot be.
2030
+ *
2031
+ * The render arm builds `container[border, innerStack]` where every inner block
2032
+ * sits in its own single-child `wrapper`, so the tail entity is
2033
+ * `innerStack.children.at(-1).children[0]`. Only the LAST inner block may be
2034
+ * updated: the inner token list is prefix-stable exactly like the top level (a
2035
+ * growing quote keeps its earlier blocks byte-identical), so anything before the
2036
+ * tail is untouched and anything more complicated than a changed tail falls back
2037
+ * to the caller's rebuild.
2038
+ *
2039
+ * Returns `false` without mutating anything when the shape is not the simple
2040
+ * grow-the-tail case, which is the signal for the caller to rebuild. Every early
2041
+ * return has to leave the entity untouched, or a rejected reuse would leave a
2042
+ * half-updated quote on screen.
2043
+ */
2044
+ /**
2045
+ * Build one list item's spans: inline content plus its marker.
2046
+ *
2047
+ * Shared by the `list` render arm and the streamed-reuse path below, because
2048
+ * the two must produce byte-identical spans — a reused list that disagreed with
2049
+ * a rebuilt one about its marker or its entity decoding would make a streamed
2050
+ * document differ from the same source pasted at once.
2051
+ */
2052
+ /**
2053
+ * Inline spans for one table cell.
2054
+ *
2055
+ * Always returns at least one span. A cell whose markup collapses to nothing —
2056
+ * an empty cell, but also a bare `<span>`, an image, or an HTML comment, none
2057
+ * of which `collectSpans` emits for — falls back to its decoded source text,
2058
+ * which is what the previous string-returning path rendered. That guarantee is
2059
+ * what lets every cell be a `RichText`: an empty cell would otherwise become a
2060
+ * `Text`, and since `Text` has `setText` while `RichText` has `setSpans` and
2061
+ * nothing converts between them, a cell that starts empty and later gains
2062
+ * content could not be updated in place. A streamed table needs exactly that,
2063
+ * because `marked` materializes a partial row as a full row of empty cells and
2064
+ * then fills them one at a time.
2065
+ */
2066
+ tableCellSpans(cell, t) {
2067
+ const spans = [];
2068
+ collectSpans(cell.tokens, {}, t, spans);
2069
+ if (spans.length === 0) spans.push({ text: decodeEntities(cell.text) });
2070
+ return spans;
2071
+ }
2072
+ /**
2073
+ * Spans for one run of consecutive non-image inline tokens.
2074
+ *
2075
+ * A paragraph holding an image renders as a `Stack` of alternating text runs
2076
+ * and images, and this is one text run. Shared by the render arm and
2077
+ * {@link updateImageParagraph} so a reused run cannot drift from a rebuilt one.
2078
+ *
2079
+ * The empty fallback mirrors `renderInlineToRichText('', …)`, which the render
2080
+ * arm passed for these runs: a run is only created when it has at least one
2081
+ * token, so the fallback is for tokens that emit no spans at all rather than
2082
+ * for an empty run.
2083
+ */
2084
+ inlineRunSpans(tokens, t) {
2085
+ const spans = [];
2086
+ if (tokens.length > 0) collectSpans(tokens, {}, t, spans);
2087
+ if (spans.length === 0) spans.push({ text: "" });
2088
+ return spans;
2089
+ }
2090
+ /** One text run of an image-bearing paragraph, as both paths build it. */
2091
+ inlineRunRichText(tokens, availableWidth, t) {
2092
+ return new import_ui.RichText(this.inlineRunSpans(tokens, t), {
2093
+ font: `${t.fontSize}px ${t.bodyFont}`,
2094
+ color: t.textColor,
2095
+ maxWidth: availableWidth,
2096
+ linkColor: "#38bdf8",
2097
+ selectable: this.selectable,
2098
+ onLinkClick: this.onLinkClick
2099
+ });
2100
+ }
2101
+ /**
2102
+ * One image inside a paragraph, sized by a guess until its bitmap decodes.
2103
+ *
2104
+ * Width and height start at a 16:10 guess because the intrinsic size is not
2105
+ * known until the browser has the bitmap; `onLoad` corrects both from
2106
+ * `naturalWidth`/`naturalHeight`. Extracted from the render arm so the streamed
2107
+ * path reuses this exact entity rather than constructing a second variant.
2108
+ *
2109
+ * `markDirty()` is unconditional, matching the display-math sibling. It used
2110
+ * to sit inside the `naturalWidth && naturalHeight` check, which meant a
2111
+ * source that loads successfully while reporting a zero dimension left the
2112
+ * scene un-notified. `Image` sets `loaded` before invoking this callback, so
2113
+ * its `render()` starts drawing the bitmap either way — the cost was not a
2114
+ * stale placeholder but a box frozen at the guess: measured on Chromium and
2115
+ * Firefox, an `<svg width="0" height="0">` paragraph image kept 800x480 of
2116
+ * reserved layout forever while a normal raster corrected to 80x60. An
2117
+ * `onDemand` scene repaints only when marked, so nothing reclaimed it.
2118
+ *
2119
+ * The box is deliberately left at the guess when the bitmap reports zero.
2120
+ * Collapsing it to 0x0 would make the paragraph reflow correctly but would
2121
+ * also silently delete a reserved region on the strength of one browser
2122
+ * quirk, and `Image.render()` still blits whatever the bitmap holds. Sizing
2123
+ * policy for a zero-dimension source is a separate decision from notifying
2124
+ * the scene, which is the actual defect here.
2125
+ */
2126
+ paragraphImage(imgToken, availableWidth) {
2127
+ const initialWidth = Math.min(800, availableWidth);
2128
+ const initialHeight = Math.round(initialWidth * 0.6);
2129
+ const img = new import_ui.Image(imgToken.href, {
2130
+ width: initialWidth,
2131
+ height: initialHeight,
2132
+ alt: imgToken.text,
2133
+ radius: 8,
2134
+ onLoad: () => {
2135
+ const bmp = img.bitmap;
2136
+ if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
2137
+ const aspect = bmp.naturalHeight / bmp.naturalWidth;
2138
+ img.width = Math.min(bmp.naturalWidth, availableWidth);
2139
+ img.height = Math.round(img.width * aspect);
2140
+ }
2141
+ this.scene?.markDirty();
2142
+ }
2143
+ });
2144
+ return img;
2145
+ }
2146
+ /** One table cell entity, shared by the render arm and the streamed-table path. */
2147
+ tableCellRichText(cell, header, t) {
2148
+ return new import_ui.RichText(this.tableCellSpans(cell, t), {
2149
+ font: `${t.fontSize - 2}px ${t.bodyFont}`,
2150
+ color: header ? t.headingColor : t.textColor,
2151
+ baseStyle: header ? { bold: true } : void 0,
2152
+ linkColor: "#38bdf8",
2153
+ selectable: this.selectable,
2154
+ onLinkClick: this.onLinkClick
2155
+ });
2156
+ }
2157
+ listItemSpans(token, index) {
2158
+ const item = token.items[index];
2159
+ const num = Number(token.start ?? 1) + index;
2160
+ const contentSpans = [];
2161
+ if (item.tokens && item.tokens.length > 0) {
2162
+ for (const inner of item.tokens) {
2163
+ if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
2164
+ collectSpans(
2165
+ inner.tokens,
2166
+ {},
2167
+ this.theme,
2168
+ contentSpans
2169
+ );
2170
+ } else if ("tokens" in inner && inner.tokens?.length) {
2171
+ collectSpans(
2172
+ inner.tokens,
2173
+ {},
2174
+ this.theme,
2175
+ contentSpans
2176
+ );
2177
+ } else if ("text" in inner) {
2178
+ contentSpans.push({ text: decodeEntities(inner.text) });
2179
+ }
2180
+ }
2181
+ } else {
2182
+ contentSpans.push({ text: decodeEntities(item.text) });
2183
+ }
2184
+ const itemIsRtl = import_core.BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
2185
+ return itemIsRtl ? [...contentSpans, { text: token.ordered ? ` .${num}` : " \u2022" }] : [{ text: token.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
2186
+ }
2187
+ /** Construct the `RichText` for one list item. */
2188
+ listItemRichText(token, index, availableWidth, t) {
2189
+ return new import_ui.RichText(this.listItemSpans(token, index), {
2190
+ font: `${t.fontSize}px ${t.bodyFont}`,
2191
+ color: t.textColor,
2192
+ maxWidth: availableWidth,
2193
+ linkColor: "#38bdf8",
2194
+ selectable: this.selectable,
2195
+ onLinkClick: this.onLinkClick
2196
+ });
2197
+ }
2198
+ /**
2199
+ * Reuse a streamed list's `Stack` instead of rebuilding every item.
2200
+ *
2201
+ * Returns `false` to mean "rebuild instead", exactly like
2202
+ * {@link updateBlockquoteTail}, and every rejection path leaves the entity
2203
+ * untouched so a refused reuse cannot leave a half-updated list on screen.
2204
+ *
2205
+ * This is the shape a stream actually produces: items are APPENDED, and only
2206
+ * the last one grows. That matters for the ordinal marker, which is
2207
+ * position-derived (`start + index`) — under append an already-rendered item's
2208
+ * index never changes, so its marker stays correct. A mid-list insertion would
2209
+ * shift every later ordinal, but no stream produces one.
2210
+ *
2211
+ * Two traps this guards, both found by probing marked 18.0.7 rather than by
2212
+ * reading:
2213
+ *
2214
+ * - **A retained item's `raw` is NOT stable.** `items[1].raw` goes `"- two"` ->
2215
+ * `"- two\\n"` when item 3 arrives, so a byte-equality guard on `raw` fails on
2216
+ * every chunk and the fast path would never fire. `text` is stable; compare
2217
+ * that.
2218
+ * - **A tight list can become loose.** Adding a blank line flips
2219
+ * `token.loose`, which re-lexes every item's children from `text` to
2220
+ * `paragraph`. Item 0's own `text` is unchanged, so a naive guard would reuse
2221
+ * and keep stale spans. Bail when `loose` flips.
2222
+ */
2223
+ updateStreamedList(stack, oldToken, newToken) {
2224
+ if (!(stack instanceof import_ui.Stack)) return false;
2225
+ if (newToken.items.length < oldToken.items.length || oldToken.items.length === 0) return false;
2226
+ if (oldToken.ordered !== newToken.ordered) return false;
2227
+ if ((oldToken.start ?? 1) !== (newToken.start ?? 1)) return false;
2228
+ if (oldToken.loose !== newToken.loose) return false;
2229
+ if (stack.children.length !== oldToken.items.length) return false;
2230
+ const lastRetained = oldToken.items.length - 1;
2231
+ for (let i = 0; i < lastRetained; i++) {
2232
+ if (oldToken.items[i].text !== newToken.items[i].text) return false;
2233
+ }
2234
+ const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
2235
+ const t = this.theme;
2236
+ const tailEntity = stack.children[lastRetained];
2237
+ if (oldToken.items[lastRetained].text !== newToken.items[lastRetained].text) {
2238
+ if (!("setSpans" in tailEntity)) return false;
2239
+ tailEntity.setSpans(
2240
+ this.listItemSpans(newToken, lastRetained)
2241
+ );
2242
+ }
2243
+ for (let i = oldToken.items.length; i < newToken.items.length; i++) {
2244
+ stack.add(this.listItemRichText(newToken, i, availableWidth, t));
2245
+ }
2246
+ const last = stack.children.at(-1);
2247
+ if (last) stack.resizeLastChild(last);
2248
+ return true;
2249
+ }
2250
+ /**
2251
+ * Reuse a streamed image-bearing paragraph's `Stack` instead of rebuilding it.
2252
+ *
2253
+ * Returns `false` to mean "rebuild instead", and every rejection happens before
2254
+ * any mutation, so a refused reuse leaves the entity exactly as it was.
2255
+ *
2256
+ * This was the last silent fallthrough in the in-place reuse path. A paragraph
2257
+ * holding an image renders as a `Stack` of alternating text runs and images
2258
+ * rather than one `RichText`, so it has no `setSpans` and failed the ordinary
2259
+ * paragraph gate — with no `else`, which is what made the miss invisible:
2260
+ * `inPlaceUpdates` stayed flat while `entitiesRebuilt` climbed. Measured on a
2261
+ * six-chunk stream, `inPlaceUpdates` 0 / `entitiesRebuilt` 4 with an image
2262
+ * against 4 / 0 for the identical shape without one. Every rebuild also
2263
+ * re-created the `Image`, discarding its decoded bitmap and its corrected
2264
+ * intrinsic size.
2265
+ *
2266
+ * It is *only* a performance path. The obvious worry — that a fresh `Image`
2267
+ * starts at `loaded = false` and so repaints its placeholder slab — was
2268
+ * measured and does not happen: sampling the real canvas pixel at the image
2269
+ * centre in both Chromium and Firefox gives zero placeholder frames after the
2270
+ * first paint, at 60ms and at 0ms between chunks, because a cached bitmap
2271
+ * decodes before the next frame.
2272
+ *
2273
+ * The reuse is deliberately narrow: **only a growing trailing text run**. Probed
2274
+ * against `marked@18.0.7`, that is the shape a stream actually produces once an
2275
+ * image has closed — the image token's `raw` and its index are then stable while
2276
+ * trailing prose grows, and the token list settles at
2277
+ * `[…, image, text]` and stops changing length. Anything else (a new image
2278
+ * arriving, an image token changing, a run appearing before the last image)
2279
+ * falls through to the rebuild, which is correct and rare.
2280
+ *
2281
+ * Note the child list is not one entity per token: consecutive non-image tokens
2282
+ * are merged into one `RichText` by the render arm's `flushText`, so
2283
+ * `[text, text, image]` is two children, not three. The guards therefore compare
2284
+ * *token runs* split at the last image, never token index against child index.
2285
+ */
2286
+ updateImageParagraph(entity, oldToken, newToken) {
2287
+ if (!(entity instanceof import_ui.Stack)) return false;
2288
+ const oldTokens = oldToken.tokens;
2289
+ const newTokens = newToken.tokens;
2290
+ if (!oldTokens || !newTokens) return false;
2291
+ const oldLastImage = lastIndexOfImage(oldTokens);
2292
+ const newLastImage = lastIndexOfImage(newTokens);
2293
+ if (oldLastImage < 0 || newLastImage < 0) return false;
2294
+ if (oldLastImage !== newLastImage) return false;
2295
+ for (let i = 0; i <= newLastImage; i++) {
2296
+ if (oldTokens[i].raw !== newTokens[i].raw) return false;
2297
+ }
2298
+ const oldTail = oldTokens.slice(oldLastImage + 1);
2299
+ const newTail = newTokens.slice(newLastImage + 1);
2300
+ if (newTail.length === 0) return false;
2301
+ const oldTailRaw = oldTail.map((t2) => t2.raw).join("");
2302
+ const newTailRaw = newTail.map((t2) => t2.raw).join("");
2303
+ if (!newTailRaw.startsWith(oldTailRaw)) return false;
2304
+ const expectedOldChildren = expectedImageParagraphChildren(oldTokens);
2305
+ if (entity.children.length !== expectedOldChildren) return false;
2306
+ const t = this.theme;
2307
+ const availableWidth = this.activeBlockMetrics?.availableWidth ?? this.maxWidth;
2308
+ if (oldTail.length === 0) {
2309
+ entity.add(this.inlineRunRichText(newTail, availableWidth, t));
2310
+ } else {
2311
+ const tailEntity = entity.children[entity.children.length - 1];
2312
+ if (!(tailEntity instanceof import_ui.RichText)) return false;
2313
+ tailEntity.setSpans(this.inlineRunSpans(newTail, t));
2314
+ }
2315
+ const last = entity.children[entity.children.length - 1];
2316
+ if (last) entity.resizeLastChild(last);
2317
+ return true;
2318
+ }
2319
+ /**
2320
+ * Reuse a streamed table's `Table` entity instead of rebuilding every cell.
2321
+ *
2322
+ * Returns `false` to mean "rebuild instead", and every rejection happens before
2323
+ * any mutation, so a refused reuse leaves the entity exactly as it was.
2324
+ *
2325
+ * A `table` token carries every row, so the rebuild path costs Θ(C·N²)
2326
+ * `RichText` constructions across a stream — and a further 2×, because
2327
+ * `Table.layout()` re-runs `fitCell` on every cell. This was the last block
2328
+ * type without an in-place path.
2329
+ *
2330
+ * Two shapes have to be handled, because of how `marked` lexes a growing table
2331
+ * (probed against 18.0.7): a partial row is materialized immediately as a FULL
2332
+ * row padded with empty cells, and its cells are then filled one at a time. A
2333
+ * 2×2 table passes through eleven distinct row states, of which only two are
2334
+ * clean row appends. So handling appends alone would reject most chunks and
2335
+ * leave the quadratic cost essentially in place:
2336
+ *
2337
+ * 1. the last row's cells are rewritten in place via `setSpans`, and
2338
+ * 2. genuinely new rows go through `Table.appendRows`.
2339
+ *
2340
+ * Cells are compared by `text`, never `raw` — a table cell has no `raw` at all
2341
+ * (its keys are `text`/`tokens`/`header`/`align`).
2342
+ */
2343
+ updateStreamedTable(entity, oldToken, newToken) {
2344
+ if (!(entity instanceof import_ui.Table)) return false;
2345
+ if (oldToken.header.length !== newToken.header.length) return false;
2346
+ for (let c = 0; c < oldToken.header.length; c++) {
2347
+ if (oldToken.header[c].text !== newToken.header[c].text) return false;
2348
+ }
2349
+ if (newToken.rows.length < oldToken.rows.length) return false;
2350
+ if (entity.rows.length !== oldToken.rows.length) return false;
2351
+ const lastRetained = oldToken.rows.length - 1;
2352
+ for (let r = 0; r < lastRetained; r++) {
2353
+ const oldRow = oldToken.rows[r];
2354
+ const newRow = newToken.rows[r];
2355
+ for (let c = 0; c < oldToken.header.length; c++) {
2356
+ if (oldRow[c]?.text !== newRow[c]?.text) return false;
2357
+ }
2358
+ }
2359
+ if (lastRetained >= 0) {
2360
+ for (let c = 0; c < oldToken.header.length; c++) {
2361
+ const cell = entity.rows[lastRetained]?.[c];
2362
+ if (!(cell instanceof import_ui.RichText)) return false;
2363
+ }
2364
+ }
2365
+ const t = this.theme;
2366
+ let changed = false;
2367
+ if (lastRetained >= 0) {
2368
+ const oldRow = oldToken.rows[lastRetained];
2369
+ const newRow = newToken.rows[lastRetained];
2370
+ for (let c = 0; c < oldToken.header.length; c++) {
2371
+ if (oldRow[c]?.text === newRow[c]?.text) continue;
2372
+ const cell = entity.rows[lastRetained][c];
2373
+ cell.setSpans(this.tableCellSpans(newRow[c], t));
2374
+ changed = true;
2375
+ }
2376
+ }
2377
+ if (newToken.rows.length > oldToken.rows.length) {
2378
+ const added = newToken.rows.slice(oldToken.rows.length).map((row) => row.map((cell) => this.tableCellRichText(cell, false, t)));
2379
+ entity.appendRows(added);
2380
+ } else if (changed) {
2381
+ entity.layout();
2382
+ }
2383
+ return true;
2384
+ }
2385
+ updateBlockquoteTail(container, oldInner, newInner) {
2386
+ if (oldInner.length !== newInner.length || newInner.length === 0) return false;
2387
+ const tail = newInner.length - 1;
2388
+ for (let i = 0; i < tail; i++) {
2389
+ if (oldInner[i].raw !== newInner[i].raw) return false;
2390
+ }
2391
+ const oldTail = oldInner[tail];
2392
+ const newTail = newInner[tail];
2393
+ if (oldTail.type !== newTail.type) return false;
2394
+ const innerStack = container.children[1];
2395
+ if (!(innerStack instanceof import_ui.Stack)) return false;
2396
+ const wrapper = innerStack.children.at(-1);
2397
+ if (!wrapper || wrapper.children.length !== 1) return false;
2398
+ const entity = wrapper.children[0];
2399
+ if (!this.producesEntity(newTail)) return false;
2400
+ if (newTail.type === "paragraph" && "setSpans" in entity) {
2401
+ entity.setSpans(
2402
+ this.literalParagraphSpans(newTail)
2403
+ );
2404
+ } else if (newTail.type === "heading" && "setSpans" in entity) {
2405
+ if (oldTail.depth !== newTail.depth) {
2406
+ return false;
2407
+ }
2408
+ entity.setSpans(
2409
+ this.headingSpans(newTail)
2410
+ );
2411
+ } else if (newTail.type === "code" && entity instanceof CodeBlock && !rendersAsMath(newTail)) {
2412
+ const codeToken = newTail;
2413
+ entity.setCode(codeToken.text, codeToken.lang ?? void 0);
2414
+ } else {
2415
+ return false;
2416
+ }
2417
+ wrapper.width = entity.x + entity.width;
2418
+ wrapper.height = entity.height;
2419
+ innerStack.resizeLastChild(wrapper);
2420
+ const border = container.children[0];
2421
+ if (border instanceof QuoteBorder) border.height = innerStack.height || 20;
2422
+ container.height = Math.max(border?.height ?? 0, innerStack.height);
2423
+ return true;
2424
+ }
2425
+ /**
2426
+ * Spans for a heading being updated in place.
2427
+ *
2428
+ * Kept in lockstep with the `heading` arm of {@link renderToken}, which builds
2429
+ * its `RichText` through `renderInlineToRichText`: same `collectSpans` call and
2430
+ * the same `decodeEntities` fallback when a heading has no inline tokens (`##`
2431
+ * with no text yet, which a stream produces before its first word arrives). A
2432
+ * plain `token.text` fallback here would leave an entity-bearing heading
2433
+ * undecoded on the in-place path but decoded on a fresh render.
2434
+ */
2435
+ headingSpans(token) {
2436
+ const spans = [];
2437
+ if (token.tokens && token.tokens.length > 0) {
2438
+ collectSpans(token.tokens, {}, this.theme, spans);
2439
+ }
2440
+ if (spans.length === 0) spans.push({ text: decodeEntities(token.text) });
2441
+ return spans;
2442
+ }
2443
+ /**
2444
+ * Spans for the trailing paragraph with its last unclosed inline construct
2445
+ * rendered as though it had closed, or `null` when there is nothing to guess.
2446
+ *
2447
+ * `null` is the answer for every `'literal'` stream, every closed or absent
2448
+ * stream, and any trailing paragraph whose syntax is all balanced — so the
2449
+ * caller falls back to {@link literalParagraphSpans} and pays nothing.
2450
+ *
2451
+ * Only the paragraph's LAST inline token is scanned. An unclosed construct can
2452
+ * only be there: anything that closed is already its own `strong`/`em`/
2453
+ * `codespan`/`link` token, so a syntax character surviving into a trailing
2454
+ * plain-text run is one `marked` could not pair. Scanning the whole raw string
2455
+ * instead would re-find the markers of already-closed constructs.
2456
+ */
2457
+ optimisticParagraphSpans(token) {
2458
+ if (this.streamIncompleteMode !== "optimistic") return null;
2459
+ if (this.streamController?.state !== "open") return null;
2460
+ const inline = token.tokens;
2461
+ if (!inline || inline.length === 0) return null;
2462
+ let runLength = 1;
2463
+ let runText;
2464
+ const last = inline[inline.length - 1];
2465
+ const prev = inline.length > 1 ? inline[inline.length - 2] : null;
2466
+ const isFlatText = (token2) => token2.type === "text" && !token2.tokens?.length;
2467
+ if (last.type === "link" && last.raw === last.text && prev !== null && isFlatText(prev) && prev.text.endsWith("](")) {
2468
+ runLength = 2;
2469
+ runText = prev.text + last.raw;
2470
+ } else if (isFlatText(last)) {
2471
+ runText = last.text;
2472
+ } else {
2473
+ return null;
2474
+ }
2475
+ const found = findUnclosedInline(runText);
2476
+ if (!found) return null;
2477
+ const spans = [];
2478
+ if (inline.length > runLength) {
2479
+ collectSpans(inline.slice(0, -runLength), {}, this.theme, spans);
2480
+ }
2481
+ const head = runText.slice(0, found.at);
2482
+ if (head) spans.push({ text: decodeEntities(head) });
2483
+ let content = runText.slice(found.contentAt);
2484
+ if (found.kind === "link") {
2485
+ const close = content.indexOf("](");
2486
+ if (close !== -1) content = content.slice(0, close);
2487
+ }
2488
+ if (!content) return null;
2489
+ const style = this.optimisticStyle(found.kind);
2490
+ spans.push({ text: decodeEntities(content), style });
2491
+ return spans;
2492
+ }
2493
+ /** Display style for a guessed-closed construct. */
2494
+ optimisticStyle(kind) {
2495
+ switch (kind) {
2496
+ case "strong":
2497
+ return { bold: true };
2498
+ case "em":
2499
+ return { italic: true };
2500
+ case "codespan":
2501
+ return { color: this.theme.codeColor, fontFamily: this.theme.codeFont };
2502
+ // A link with no closing paren has no href, so it renders as plain text —
2503
+ // no link color and no click affordance for a destination nobody has yet.
2504
+ case "link":
2505
+ return void 0;
2506
+ }
2507
+ }
2508
+ /**
2509
+ * Re-render the paragraph currently showing a guess from its own tokens, with
2510
+ * no overlay, and forget it.
2511
+ *
2512
+ * Idempotent and free when no guess is live, which is what lets `close()`,
2513
+ * `abort()`, and a mid-stream staleness check all call it unconditionally.
2514
+ */
2515
+ /**
2516
+ * Start the MathJax load, and re-typeset this document once it resolves.
2517
+ *
2518
+ * Called from two places, for two different reasons:
2519
+ *
2520
+ * - When an OPEN math fence is rendered. This is a prefetch, and it is what
2521
+ * makes the lazy load invisible while streaming: the module starts loading
2522
+ * the moment a formula begins arriving, several chunks before its closing
2523
+ * fence, so by the time the fence closes the converter is usually already
2524
+ * installed and the formula typesets synchronously on the normal path.
2525
+ * - When a CLOSED fence could not be typeset because the module is not ready.
2526
+ * That is the case a rebuild actually exists for: a document constructed with
2527
+ * math already complete, or a stream that closed a fence faster than the
2528
+ * module loaded.
2529
+ *
2530
+ * Idempotent per instance. Concurrent callers coalesce onto the one cached
2531
+ * module promise, and `mathLoadPending` keeps a second rebuild from being
2532
+ * queued while the first is outstanding.
2533
+ */
2534
+ ensureMathJax() {
2535
+ if (mathConverter || this.mathLoadPending || this.isDestroyed) return;
2536
+ this.mathLoadPending = true;
2537
+ void preloadMathJax().then(() => {
2538
+ this.mathLoadPending = false;
2539
+ if (this.isDestroyed) return;
2540
+ if (mathConverter) this.retypesetFromTokens();
2541
+ this.flushAppendSettledWaiters();
2542
+ });
2543
+ }
2544
+ /**
2545
+ * Rebuild every block from the tokens already lexed, without re-lexing.
2546
+ *
2547
+ * Used only when MathJax arrives after a formula has already been rendered as
2548
+ * source. Rebuilding wholesale rather than surgically replacing the math blocks
2549
+ * is the deliberate choice: `tokenChildPrefix` maps token indices to child
2550
+ * slots positionally, so swapping one child in place would have to keep that
2551
+ * mapping, the `Stack`'s cached box, and every following sibling's position in
2552
+ * agreement by hand. Re-rendering the same token list in the same order leaves
2553
+ * the mapping trivially correct, and this runs at most once per document — the
2554
+ * same cost as the `setContent` rebuild that already exists.
2555
+ *
2556
+ * The optimistic tail is dropped first. Its `entity` is about to be destroyed,
2557
+ * so the pointer would dangle; unwinding restores literal spans, and if the
2558
+ * stream is still open the next chunk re-applies a guess.
2559
+ */
2560
+ retypesetFromTokens() {
2561
+ this.unwindOptimisticTail();
2562
+ const tokens = this.tokens;
2563
+ while (this.content.children.length > 0) {
2564
+ this.content.children[this.content.children.length - 1].destroy();
2565
+ }
2566
+ for (const token of tokens) {
2567
+ const el = this.renderToken(token);
2568
+ if (el) this.content.add(el);
2569
+ }
2570
+ this.width = this.content.width;
2571
+ this.height = this.content.height;
2572
+ this.scene?.markDirty();
2573
+ }
2574
+ unwindOptimisticTail() {
2575
+ const tail = this.optimisticTail;
2576
+ this.optimisticTail = null;
2577
+ if (!tail || this.isDestroyed) return;
2578
+ const entity = tail.entity;
2579
+ if (!entity.setSpans || entity.parent !== this.content) return;
2580
+ entity.setSpans(this.literalParagraphSpans(tail.token));
2581
+ if (this.content.children.at(-1) === entity) {
2582
+ this.content.resizeLastChild(entity);
2583
+ } else {
2584
+ this.content.layout();
2585
+ }
2586
+ this.width = this.content.width;
2587
+ this.height = this.content.height;
2588
+ this.scene?.markDirty();
2589
+ }
2590
+ /**
2591
+ * Drop a guess that is no longer on the document's trailing paragraph.
2592
+ *
2593
+ * A coalesced append can add a block after the paragraph that owns the guess,
2594
+ * at which point the guess is frozen — the construct can never close, because
2595
+ * no further text lands in that paragraph. Without this the stale styling would
2596
+ * survive until `close()`.
2597
+ *
2598
+ * `writtenThisPass` is the entity whose spans this reconcile already rewrote,
2599
+ * if any: for that one, literal spans are on screen already and re-rendering it
2600
+ * would be wasted layout, so only the bookkeeping is cleared.
2601
+ */
2602
+ dropStaleOptimisticTail(trailing, writtenThisPass) {
2603
+ const tail = this.optimisticTail;
2604
+ if (!tail || tail.entity === trailing) return;
2605
+ if (tail.entity === writtenThisPass) {
2606
+ this.optimisticTail = null;
2607
+ return;
2608
+ }
2609
+ this.unwindOptimisticTail();
2610
+ }
2611
+ /**
2612
+ * Resolve once every in-flight worker append has actually been applied.
2613
+ *
2614
+ * Committing text is not the same as the document reflecting it: `append()`
2615
+ * reaches `dispatchAppend()`, which `postMessage()`s and returns, and the reply
2616
+ * that runs `updateTokens()` lands later. Without waiting here, `close()` could
2617
+ * resolve — and `onStable` fire — against a document missing its last chunk.
2618
+ *
2619
+ * An outstanding lazy MathJax load counts as unsettled for the same reason. A
2620
+ * document whose formulas are still TeX source is not final in any sense a
2621
+ * caller of `onStable` cares about: the boxes are the wrong size, so measuring
2622
+ * or exporting there would capture placeholders.
2623
+ */
2624
+ waitForAppendSettled() {
2625
+ if (!this.appendInFlight && !this.mathLoadPending) return Promise.resolve();
2626
+ return new Promise((resolve) => {
2627
+ this.appendSettledWaiters.push(resolve);
2628
+ });
2629
+ }
2630
+ /**
2631
+ * Release settlement waiters, but only once nothing is outstanding.
2632
+ *
2633
+ * Called at the very END of the worker callback, after its coalesced-re-dispatch
2634
+ * check, rather than wherever `appendInFlight` goes false. Within that callback
2635
+ * `appendInFlight` is cleared and then, if another chunk arrived while the
2636
+ * request was in flight, set straight back to `true` by the re-dispatch — both
2637
+ * synchronously, before anything watching the flag could observe the gap. Only
2638
+ * checking here, after that, waits through the re-dispatch instead of resolving
2639
+ * one chunk early.
2640
+ */
2641
+ flushAppendSettledWaiters() {
2642
+ if (this.appendInFlight || this.mathLoadPending || this.appendSettledWaiters.length === 0) {
2643
+ return;
2644
+ }
2645
+ const waiters = this.appendSettledWaiters;
2646
+ this.appendSettledWaiters = [];
2647
+ for (const resolve of waiters) resolve();
2648
+ }
2649
+ /** Throw if a public mutation is attempted from inside an `onStable` callback. */
2650
+ assertNotInStableCallback(method) {
2651
+ if (this.inStableCallback) {
2652
+ throw new Error(`Markdown.${method}() cannot be called from an onStable callback`);
2653
+ }
2654
+ }
1636
2655
  updateTokens(newTokens, knownMatchLen) {
1637
2656
  const oldTokens = this.tokens;
1638
2657
  const oldChildren = [...this.content.children];
@@ -1652,11 +2671,18 @@ var Markdown = class extends import_ui.UIComponent {
1652
2671
  }
1653
2672
  const oldTokenToChild = this.tokenChildPrefix;
1654
2673
  const rawMatchLen = matchLen;
2674
+ let pendingTail = null;
2675
+ let spansWrittenTo = null;
1655
2676
  const lastTokenSameType = matchLen === oldTokens.length - 1 && matchLen < newTokens.length && oldTokens[matchLen]?.type === newTokens[matchLen]?.type;
1656
2677
  if (lastTokenSameType && newTokens[matchLen]?.type === "code") {
1657
2678
  const existingEntity = oldChildren[oldTokenToChild[matchLen]];
1658
2679
  const codeToken = newTokens[matchLen];
1659
- if (existingEntity instanceof CodeBlock) {
2680
+ const oldCodeToken = oldTokens[matchLen];
2681
+ const isMath = rendersAsMath(codeToken);
2682
+ if (isMath && rendersAsMath(oldCodeToken) && oldCodeToken.text === codeToken.text) {
2683
+ this.streamStats.inPlaceUpdates++;
2684
+ matchLen++;
2685
+ } else if (existingEntity instanceof CodeBlock && !isMath) {
1660
2686
  existingEntity.setCode(codeToken.text, codeToken.lang ?? void 0);
1661
2687
  this.streamStats.inPlaceUpdates++;
1662
2688
  matchLen++;
@@ -1665,17 +2691,63 @@ var Markdown = class extends import_ui.UIComponent {
1665
2691
  } else if (lastTokenSameType && newTokens[matchLen]?.type === "paragraph") {
1666
2692
  const entityIdx = oldTokenToChild[matchLen];
1667
2693
  const existingEntity = oldChildren[entityIdx];
1668
- if (existingEntity && "setSpans" in existingEntity) {
2694
+ if (existingEntity && "setSpans" in existingEntity && !paragraphHasImage(newTokens[matchLen])) {
1669
2695
  const pToken = newTokens[matchLen];
1670
- const t = this.theme;
1671
- const spans = [];
1672
- if (pToken.tokens && pToken.tokens.length > 0) {
1673
- collectSpans(pToken.tokens, {}, t, spans);
1674
- }
1675
- if (spans.length === 0) {
1676
- spans.push({ text: pToken.text });
1677
- }
1678
- existingEntity.setSpans(spans);
2696
+ const isTrailing = matchLen === newTokens.length - 1;
2697
+ const optimistic = isTrailing ? this.optimisticParagraphSpans(pToken) : null;
2698
+ existingEntity.setSpans(optimistic ?? this.literalParagraphSpans(pToken));
2699
+ spansWrittenTo = existingEntity;
2700
+ if (optimistic) pendingTail = { entity: existingEntity, token: pToken };
2701
+ this.streamStats.inPlaceUpdates++;
2702
+ matchLen++;
2703
+ this.content.resizeLastChild(existingEntity);
2704
+ } else if (existingEntity && this.updateImageParagraph(
2705
+ existingEntity,
2706
+ oldTokens[matchLen],
2707
+ newTokens[matchLen]
2708
+ )) {
2709
+ this.streamStats.inPlaceUpdates++;
2710
+ matchLen++;
2711
+ this.content.resizeLastChild(existingEntity);
2712
+ }
2713
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "heading") {
2714
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2715
+ const hToken = newTokens[matchLen];
2716
+ const oldToken = oldTokens[matchLen];
2717
+ if (existingEntity && "setSpans" in existingEntity && oldToken?.depth === hToken.depth) {
2718
+ existingEntity.setSpans(this.headingSpans(hToken));
2719
+ spansWrittenTo = existingEntity;
2720
+ this.streamStats.inPlaceUpdates++;
2721
+ matchLen++;
2722
+ this.content.resizeLastChild(existingEntity);
2723
+ }
2724
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "blockquote") {
2725
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2726
+ const newInner = newTokens[matchLen].tokens;
2727
+ const oldInner = oldTokens[matchLen].tokens;
2728
+ if (existingEntity instanceof MarkdownContainer && newInner && oldInner && this.updateBlockquoteTail(existingEntity, oldInner, newInner)) {
2729
+ this.streamStats.inPlaceUpdates++;
2730
+ matchLen++;
2731
+ this.content.resizeLastChild(existingEntity);
2732
+ }
2733
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "list") {
2734
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2735
+ if (existingEntity && this.updateStreamedList(
2736
+ existingEntity,
2737
+ oldTokens[matchLen],
2738
+ newTokens[matchLen]
2739
+ )) {
2740
+ this.streamStats.inPlaceUpdates++;
2741
+ matchLen++;
2742
+ this.content.resizeLastChild(existingEntity);
2743
+ }
2744
+ } else if (lastTokenSameType && newTokens[matchLen]?.type === "table") {
2745
+ const existingEntity = oldChildren[oldTokenToChild[matchLen]];
2746
+ if (existingEntity && this.updateStreamedTable(
2747
+ existingEntity,
2748
+ oldTokens[matchLen],
2749
+ newTokens[matchLen]
2750
+ )) {
1679
2751
  this.streamStats.inPlaceUpdates++;
1680
2752
  matchLen++;
1681
2753
  this.content.resizeLastChild(existingEntity);
@@ -1693,10 +2765,24 @@ var Markdown = class extends import_ui.UIComponent {
1693
2765
  }
1694
2766
  }
1695
2767
  }
2768
+ const lastIndex = newTokens.length - 1;
1696
2769
  for (let i = matchLen; i < newTokens.length; i++) {
1697
2770
  const el = this.renderToken(newTokens[i]);
1698
- if (el) this.content.add(el);
2771
+ if (!el) continue;
2772
+ this.content.add(el);
2773
+ if (i === lastIndex && newTokens[i].type === "paragraph" && "setSpans" in el) {
2774
+ const pToken = newTokens[i];
2775
+ const optimistic = this.optimisticParagraphSpans(pToken);
2776
+ if (optimistic) {
2777
+ el.setSpans(optimistic);
2778
+ this.content.resizeLastChild(el);
2779
+ pendingTail = { entity: el, token: pToken };
2780
+ spansWrittenTo = el;
2781
+ }
2782
+ }
1699
2783
  }
2784
+ this.dropStaleOptimisticTail(pendingTail?.entity ?? null, spansWrittenTo);
2785
+ if (pendingTail) this.optimisticTail = pendingTail;
1700
2786
  this.setTokens(newTokens, rawMatchLen);
1701
2787
  this.width = this.content.width;
1702
2788
  this.height = this.content.height;
@@ -1749,6 +2835,43 @@ var Markdown = class extends import_ui.UIComponent {
1749
2835
  return "text" in token;
1750
2836
  }
1751
2837
  }
2838
+ /**
2839
+ * Build a centered display-math block, or `null` if MathJax cannot typeset yet.
2840
+ *
2841
+ * Shared by the `$$..$$` block token and a closed ```` ```math ```` fence:
2842
+ * both are display math and must render identically, differing only in how
2843
+ * they were spelled in the source.
2844
+ *
2845
+ * `ex` is font-relative, so the intrinsic box is resolved against the theme's
2846
+ * body size. This is what a previously hardcoded `* 8` got wrong -- exact only
2847
+ * near fontSize 18.1px, so a formula was ~13% oversized at the 16px default
2848
+ * and far worse at other sizes.
2849
+ */
2850
+ renderDisplayMath(formula, availableWidth) {
2851
+ const t = this.theme;
2852
+ const mathData = renderMathToSVGDataURI(formula, true, t.textColor);
2853
+ if (!mathData) return null;
2854
+ const intrinsicW = exToPx(mathData.widthEx, t.fontSize);
2855
+ const intrinsicH = exToPx(mathData.heightEx, t.fontSize);
2856
+ const mathImg = new import_ui.Image(mathData.uri, {
2857
+ width: Math.min(availableWidth, intrinsicW),
2858
+ height: intrinsicH * Math.min(1, availableWidth / intrinsicW),
2859
+ alt: formula,
2860
+ // The SVG decodes asynchronously and Image paints a placeholder until it
2861
+ // lands. Without this an `onDemand` scene, which repaints only when marked
2862
+ // dirty, leaves the formula a blank slab forever.
2863
+ onLoad: () => {
2864
+ this.scene?.markDirty();
2865
+ }
2866
+ });
2867
+ const wrapper = new MarkdownContainer();
2868
+ mathImg.x = 16;
2869
+ mathImg.y = 8;
2870
+ wrapper.add(mathImg);
2871
+ wrapper.width = mathImg.width + 16;
2872
+ wrapper.height = mathImg.height + 16;
2873
+ return wrapper;
2874
+ }
1752
2875
  renderToken(token) {
1753
2876
  const t = this.theme;
1754
2877
  const bodyFont = `${t.fontSize}px ${t.bodyFont}`;
@@ -1759,6 +2882,10 @@ var Markdown = class extends import_ui.UIComponent {
1759
2882
  availableWidth: this.maxWidth
1760
2883
  };
1761
2884
  const availableWidth = metrics.availableWidth;
2885
+ if (containsInlineMath(token)) {
2886
+ if (!mathConverter) this.ensureMathJax();
2887
+ this.subscribeInlineMathRepaint();
2888
+ }
1762
2889
  switch (token.type) {
1763
2890
  // ── Headings ─────────────────────────────────────────────────────
1764
2891
  case "heading": {
@@ -1780,7 +2907,7 @@ var Markdown = class extends import_ui.UIComponent {
1780
2907
  // ── Paragraphs ───────────────────────────────────────────────────
1781
2908
  case "paragraph": {
1782
2909
  const pToken = token;
1783
- if (!pToken.tokens || !pToken.tokens.some((t2) => t2.type === "image")) {
2910
+ if (!paragraphHasImage(pToken)) {
1784
2911
  return renderInlineToRichText(
1785
2912
  pToken.tokens,
1786
2913
  pToken.text,
@@ -1800,43 +2927,14 @@ var Markdown = class extends import_ui.UIComponent {
1800
2927
  let currentTokens = [];
1801
2928
  const flushText = () => {
1802
2929
  if (currentTokens.length > 0) {
1803
- stack.add(
1804
- renderInlineToRichText(
1805
- currentTokens,
1806
- "",
1807
- bodyFont,
1808
- t.textColor,
1809
- availableWidth,
1810
- t,
1811
- this.selectable,
1812
- this.onLinkClick
1813
- )
1814
- );
2930
+ stack.add(this.inlineRunRichText(currentTokens, availableWidth, t));
1815
2931
  currentTokens = [];
1816
2932
  }
1817
2933
  };
1818
2934
  for (const child of pToken.tokens) {
1819
2935
  if (child.type === "image") {
1820
2936
  flushText();
1821
- const imgToken = child;
1822
- const initialWidth = Math.min(800, availableWidth);
1823
- const initialHeight = Math.round(initialWidth * 0.6);
1824
- const img = new import_ui.Image(imgToken.href, {
1825
- width: initialWidth,
1826
- height: initialHeight,
1827
- alt: imgToken.text,
1828
- radius: 8,
1829
- onLoad: () => {
1830
- const bmp = img.bitmap;
1831
- if (bmp && bmp.naturalWidth && bmp.naturalHeight) {
1832
- const aspect = bmp.naturalHeight / bmp.naturalWidth;
1833
- img.width = Math.min(bmp.naturalWidth, availableWidth);
1834
- img.height = Math.round(img.width * aspect);
1835
- if (this.scene) this.scene.markDirty();
1836
- }
1837
- }
1838
- });
1839
- stack.add(img);
2937
+ stack.add(this.paragraphImage(child, availableWidth));
1840
2938
  } else {
1841
2939
  currentTokens.push(child);
1842
2940
  }
@@ -1844,26 +2942,22 @@ var Markdown = class extends import_ui.UIComponent {
1844
2942
  flushText();
1845
2943
  return stack;
1846
2944
  }
2945
+ // ── Display math (`$$..$$`) ──────────────────────────────────────
2946
+ case "blockMath": {
2947
+ const mathToken = token;
2948
+ const mathBlock = this.renderDisplayMath(mathToken.text, availableWidth);
2949
+ if (mathBlock) return mathBlock;
2950
+ this.ensureMathJax();
2951
+ return new CodeBlock(mathToken.text, "latex", availableWidth, t, this.selectable);
2952
+ }
1847
2953
  // ── Code blocks ──────────────────────────────────────────────────
1848
2954
  case "code": {
1849
2955
  const codeToken = token;
1850
2956
  const lang = (codeToken.lang ?? "").toLowerCase();
1851
- if (lang === "math" || lang === "latex" || lang === "tex") {
1852
- const mathData = renderMathToSVGDataURI(codeToken.text, true);
1853
- if (mathData) {
1854
- const mathImg = new import_ui.Image(mathData.uri, {
1855
- width: Math.min(availableWidth, mathData.width),
1856
- height: mathData.height * Math.min(1, availableWidth / mathData.width),
1857
- alt: codeToken.text
1858
- });
1859
- const wrapper = new MarkdownContainer();
1860
- mathImg.x = 16;
1861
- mathImg.y = 8;
1862
- wrapper.add(mathImg);
1863
- wrapper.width = mathImg.width + 16;
1864
- wrapper.height = mathImg.height + 16;
1865
- return wrapper;
1866
- }
2957
+ if (MATH_LANGS.has(lang)) this.ensureMathJax();
2958
+ if (rendersAsMath(codeToken)) {
2959
+ const mathBlock = this.renderDisplayMath(codeToken.text, availableWidth);
2960
+ if (mathBlock) return mathBlock;
1867
2961
  }
1868
2962
  return new CodeBlock(codeToken.text, lang, availableWidth, t, this.selectable);
1869
2963
  }
@@ -1903,62 +2997,22 @@ var Markdown = class extends import_ui.UIComponent {
1903
2997
  container.height = Math.max(border.height, innerStack.height);
1904
2998
  return container;
1905
2999
  }
1906
- // ── Lists ────────────────────────────────────────────────────────
3000
+ // ── Lists ────────────────────────────────────────────────
1907
3001
  case "list": {
1908
3002
  const listToken = token;
1909
3003
  const listStack = new import_ui.Stack({ direction: "vertical", gap: 6 });
1910
3004
  for (let i = 0; i < listToken.items.length; i++) {
1911
- const item = listToken.items[i];
1912
- const num = Number(listToken.start ?? 1) + i;
1913
- const contentSpans = [];
1914
- if (item.tokens && item.tokens.length > 0) {
1915
- for (const inner of item.tokens) {
1916
- if (inner.type === "text" && "tokens" in inner && inner.tokens?.length) {
1917
- collectSpans(inner.tokens, {}, t, contentSpans);
1918
- } else if ("tokens" in inner && inner.tokens?.length) {
1919
- collectSpans(inner.tokens, {}, t, contentSpans);
1920
- } else if ("text" in inner) {
1921
- contentSpans.push({
1922
- text: decodeEntities(inner.text)
1923
- });
1924
- }
1925
- }
1926
- } else {
1927
- contentSpans.push({ text: decodeEntities(item.text) });
1928
- }
1929
- const itemIsRtl = import_core.BidiResolver.getBaseLevel(contentSpans.map((s) => s.text).join("")) % 2 === 1;
1930
- const itemSpans = itemIsRtl ? [...contentSpans, { text: listToken.ordered ? ` .${num}` : " \u2022" }] : [{ text: listToken.ordered ? `${num}. ` : "\u2022 " }, ...contentSpans];
1931
- const itemRt = new import_ui.RichText(itemSpans, {
1932
- font: bodyFont,
1933
- color: t.textColor,
1934
- maxWidth: Math.max(0, availableWidth - 24),
1935
- linkColor: "#38bdf8",
1936
- selectable: this.selectable,
1937
- onLinkClick: this.onLinkClick
1938
- });
1939
- itemRt.x = 12;
1940
- listStack.add(itemRt);
3005
+ listStack.add(this.listItemRichText(listToken, i, availableWidth, t));
1941
3006
  }
1942
3007
  return listStack;
1943
3008
  }
1944
3009
  // ── Table ────────────────────────────────────────────────────────
1945
3010
  case "table": {
1946
3011
  const tblToken = token;
1947
- const buildCell = (cell, header) => {
1948
- const spans = [];
1949
- collectSpans(cell.tokens, {}, t, spans);
1950
- if (spans.length === 0) return decodeEntities(cell.text);
1951
- return new import_ui.RichText(spans, {
1952
- font: `${t.fontSize - 2}px ${t.bodyFont}`,
1953
- color: header ? t.headingColor : t.textColor,
1954
- baseStyle: header ? { bold: true } : void 0,
1955
- linkColor: "#38bdf8",
1956
- selectable: this.selectable,
1957
- onLinkClick: this.onLinkClick
1958
- });
1959
- };
1960
- const headers = tblToken.header.map((cell) => buildCell(cell, true));
1961
- const rows = tblToken.rows.map((row) => row.map((cell) => buildCell(cell, false)));
3012
+ const headers = tblToken.header.map((cell) => this.tableCellRichText(cell, true, t));
3013
+ const rows = tblToken.rows.map(
3014
+ (row) => row.map((cell) => this.tableCellRichText(cell, false, t))
3015
+ );
1962
3016
  return new import_ui.Table({
1963
3017
  headers,
1964
3018
  rows,
@@ -2009,5 +3063,7 @@ var Markdown = class extends import_ui.UIComponent {
2009
3063
  CodeBlock,
2010
3064
  Markdown,
2011
3065
  codeAtlas,
2012
- codeAtlasStats
3066
+ codeAtlasStats,
3067
+ isMathJaxReady,
3068
+ preloadMathJax
2013
3069
  });