@vectojs/markdown 0.1.2 → 0.3.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.
@@ -1,4 +1,4 @@
1
- import { Entity, IRenderer, type ContentProjection } from '@vectojs/core';
1
+ import { Entity, type DevtoolsDescriptor, GlyphRasterAtlas, type GlyphRasterAtlasStats, IRenderer, type ContentProjection } from '@vectojs/core';
2
2
  import { type Token } from 'marked';
3
3
  import { Stack, UIComponent } from '@vectojs/ui';
4
4
  /** Color and typography theme for Markdown rendering. */
@@ -71,6 +71,25 @@ export declare class CodeBlock extends UIComponent {
71
71
  isPointInside(): boolean;
72
72
  render(r: IRenderer): void;
73
73
  }
74
+ /**
75
+ * Instrumentation for the shared code-block glyph atlas, or `null` before first
76
+ * use.
77
+ *
78
+ * Exposed so an app or benchmark can confirm the atlas is actually active and
79
+ * reusing slots. Watch `resets`: a steadily climbing count means the glyph set is
80
+ * unbounded for the atlas size, so every reset re-rasterizes everything and the
81
+ * atlas is doing net harm rather than saving work.
82
+ */
83
+ export declare function codeAtlasStats(): GlyphRasterAtlasStats | null;
84
+ /**
85
+ * The shared code-block atlas itself, or `null` before first use.
86
+ *
87
+ * For instrumentation that must map a traced `drawImage` back to the glyph it
88
+ * painted — a blit carries only a source rect, so `slotAt()` is the only way to
89
+ * recover the cluster and its metrics. Used by `e2e/text-projection.e2e.ts` to
90
+ * keep the code-grid positioning assertions working on the blit path.
91
+ */
92
+ export declare function codeAtlas(): GlyphRasterAtlas | null;
74
93
  export interface MarkdownOptions {
75
94
  maxWidth?: number;
76
95
  theme?: MarkdownTheme;
@@ -105,6 +124,16 @@ export declare class Markdown extends UIComponent {
105
124
  private tokens;
106
125
  private appendInFlight;
107
126
  private appendPending;
127
+ /**
128
+ * Streaming counters for the DevTools inspector.
129
+ *
130
+ * Cheap enough to keep always-on (four integer increments per append) and the
131
+ * only way to see, from outside, whether incremental reuse is actually working:
132
+ * a stable-prefix ratio near 1 means the worker is matching almost everything
133
+ * and only the tail is re-lexed, while a ratio near 0 means every chunk is
134
+ * re-parsing the whole document.
135
+ */
136
+ private streamStats;
108
137
  private pendingWorkerIds;
109
138
  private readonly workerInstanceId;
110
139
  private tokenVersion;
@@ -130,6 +159,16 @@ export declare class Markdown extends UIComponent {
130
159
  * content subtree via `super.destroy()` so every block's resources are freed.
131
160
  */
132
161
  destroy(): void;
162
+ /**
163
+ * Streaming and parse state — the markdown streaming inspector.
164
+ *
165
+ * Source length, chunk count, worker in-flight state, and the stable-prefix
166
+ * versus re-lexed-tail split. That last ratio is the one worth watching: it is
167
+ * how you tell incremental reuse is working from outside, and nothing else
168
+ * surfaces it. A ratio near 1 means the worker matched almost the whole prefix
169
+ * and only re-lexed the tail; near 0 means every chunk re-parses the document.
170
+ */
171
+ getDevtoolsDescriptor(): DevtoolsDescriptor;
133
172
  /** Enable or disable native selection for existing and future Markdown text. */
134
173
  setSelectable(selectable: boolean): this;
135
174
  /** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
package/dist/index.js CHANGED
@@ -21,7 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  CodeBlock: () => CodeBlock,
24
- Markdown: () => Markdown
24
+ Markdown: () => Markdown,
25
+ codeAtlas: () => codeAtlas,
26
+ codeAtlasStats: () => codeAtlasStats
25
27
  });
26
28
  module.exports = __toCommonJS(index_exports);
27
29
 
@@ -40,6 +42,7 @@ var import_ui = require("@vectojs/ui");
40
42
  var WORKER_SOURCE_STRING = '"use strict";(()=>{function O(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=O();function oe(r){T=r}var R={exec:()=>null};function z(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(x.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}})(),x={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:z(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ ][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:z(r=>new RegExp(`^ {0,${r}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:z(r=>new RegExp(`^ {0,${r}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:z(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:z(r=>new RegExp(`^ {0,${r}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:z(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|$)|$)/,v=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Se=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,N=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,ce=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,he=g(ce).replace(/bull/g,N).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(ce).replace(/bull/g,N).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(),G=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,ze=/^[^\\n]+/,X=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Ae=g(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\\\"?|[^"\\\\])*"|\'[^\'\\n]*(?:\\n[^\'\\n]+)*\\n?\'|\\([^()]*\\))/).getRegex(),_e=g(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,N).getRegex(),q="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",W=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,Pe=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",W).replace("tag",q).replace("attribute",/ +[a-zA-Z:_][\\w.:-]*(?: *= *"[^"\\n]*"| *= *\'[^\'\\n]*\'| *= *[^\\s"\'=<>`]+)?/).getRegex(),pe=r=>g(G).replace("hr",v).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",q).getRegex(),Le=pe(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),ve=pe(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),Ie=g(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace("paragraph",ve).getRegex(),F={blockquote:Ie,code:$e,def:Ae,fences:Re,heading:Se,hr:v,html:Pe,lheading:he,list:_e,newline:ye,paragraph:Le,table:R,text:ze},te=g("^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)").replace("hr",v).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",q).getRegex(),Ee={...F,lheading:Te,table:te,paragraph:g(G).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("table",te).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",q).getRegex()},Ce={...F,html:g(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:"[^"]*"|\'[^\']*\'|\\\\s[^\'"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace("comment",W).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:R,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:g(G).replace("hr",v).replace("heading",` *#{1,6} *[^\n]`).replace("lheading",he).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Be=/^\\\\([!"#$%&\'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,qe=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ue=/^( {2,}|\\\\)\\n(?!\\s*$)/,Ze=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,A=/[\\p{P}\\p{S}]/u,Z=/[\\s\\p{P}\\p{S}]/u,U=/[^\\s\\p{P}\\p{S}]/u,De=g(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Z).getRegex(),ge=/(?!~)[\\p{P}\\p{S}]/u,Me=/(?!~)[\\s\\p{P}\\p{S}]/u,Qe=/(?:[^\\s\\p{P}\\p{S}]|~)/u,je=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(),ke=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,He=g(ke,"u").replace(/punct/g,A).getRegex(),Oe=g(ke,"u").replace(/punct/g,ge).getRegex(),de="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)",Ne=g(de,"gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),Ge=g(de,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Me).replace(/punct/g,ge).getRegex(),Xe=g("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),We=g(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,A).getRegex(),Fe="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ue=g(Fe,"gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),Ve=g(/\\\\(punct)/,"gu").replace(/punct/g,A).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(W).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(),E=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,et=g(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",E).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|\'(?:\\\\\'?|[^\'\\\\])*\'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),fe=g(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",E).replace("ref",X).getRegex(),xe=g(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",X).getRegex(),tt=g("reflink|nolink(?!\\\\()","g").replace("reflink",fe).replace("nolink",xe).getRegex(),re=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V={_backpedal:R,anyPunctuation:Ve,autolink:Je,blockSkip:je,br:ue,code:qe,del:R,delLDelim:R,delRDelim:R,emStrongLDelim:He,emStrongRDelimAst:Ne,emStrongRDelimUnd:Xe,escape:Be,link:et,nolink:xe,punctuation:De,reflink:fe,reflinkSearch:tt,tag:Ye,text:Ze,url:R},rt={...V,link:g(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",E).getRegex(),reflink:g(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",E).getRegex()},Q={...V,emStrongRDelimAst:Ge,emStrongLDelim:Oe,delLDelim:We,delRDelim:Ue,url:g(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",re).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",re).getRegex()},nt={...Q,br:g(ue).replace("{2,}","*").getRegex(),text:g(Q.text).replace("\\\\b_","\\\\b_| {2,}\\\\n").replace(/\\{2,\\}/g,"*").getRegex()},I={normal:F,gfm:Ee,pedantic:Ce},P={normal:V,gfm:Q,breaks:nt,pedantic:rt},st={"&":"&amp;","<":"&lt;",">":"&gt;",\'"\':"&quot;","\'":"&#39;"},ne=r=>st[r];function m(r,e){if(e){if(x.escapeTest.test(r))return r.replace(x.escapeReplace,ne)}else if(x.escapeTestNoEncode.test(r))return r.replace(x.escapeReplaceNoEncode,ne);return r}function se(r){try{r=encodeURI(r).replace(x.percentDecode,"%")}catch{return null}return r}function ie(r,e){let t=r.replace(x.findPipe,(i,a,l)=>{let o=!1,c=a;for(;--c>=0&&l[c]==="\\\\";)o=!o;return o?"|":" |"}),s=t.split(x.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(x.slashPipe,"|");return s}function $(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 le(r){let e=r.split(`\n`),t=e.length-1;for(;t>=0&&x.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 ae(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 C=class{options;rules;lexer;constructor(r){this.options=r||T}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]:le(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=$(t,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(t=s.trim())}return{type:"heading",raw:$(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:$(e[0],`\n`)}}blockquote(r){let e=this.rules.block.blockquote.exec(r);if(e){let t=$(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 f=u,d=f.raw+`\n`+t.join(`\n`),y=this.blockquote(d);i[i.length-1]=y,s=s.substring(0,s.length-f.raw.length)+y.raw,n=n.substring(0,n.length-f.text.length)+y.text;break}else if(u?.type==="list"){let f=u,d=f.raw+`\n`+t.join(`\n`),y=this.list(d);i[i.length-1]=y,s=s.substring(0,s.length-u.raw.length)+y.raw,n=n.substring(0,n.length-f.raw.length)+y.raw,t=d.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],f=!h.trim(),d=0;if(this.options.pedantic?(d=2,p=h.trimStart()):f?d=e[1].length+1:(d=h.search(this.rules.other.nonSpaceChar),d=d>4?1:d,p=h.slice(d),d+=e[1].length),f&&this.rules.other.blankLine.test(u)&&(c+=u+`\n`,r=r.substring(u.length+1),o=!0),!o){let y=this.rules.other.nextBulletRegex(d),K=this.rules.other.hrRegex(d),Y=this.rules.other.fencesBeginRegex(d),ee=this.rules.other.headingBeginRegex(d),be=this.rules.other.htmlBeginRegex(d),we=this.rules.other.blockquoteBeginRegex(d);for(;r;){let M=r.split(`\n`,1)[0],_;if(u=M,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),_=u):_=u.replace(this.rules.other.tabCharGlobal," "),Y.test(u)||ee.test(u)||be.test(u)||we.test(u)||y.test(u)||K.test(u))break;if(_.search(this.rules.other.nonSpaceChar)>=d||!u.trim())p+=`\n`+_.slice(d);else{if(f||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Y.test(h)||ee.test(h)||K.test(h))break;p+=`\n`+u}f=!u.trim(),c+=M+`\n`,r=r.substring(M.length+1),h=_.slice(d)}}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=le(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:$(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=ie(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:$(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(ie(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:$(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=$(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)),ae(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 ae(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 f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}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}}}},b=class j{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new C,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:x,block:I.normal,inline:P.normal};this.options.pedantic?(t.block=I.pedantic,t.inline=P.pedantic):this.options.gfm&&(t.block=I.gfm,this.options.breaks?t.inline=P.breaks:t.inline=P.gfm),this.tokenizer.rules=t}static get rules(){return{block:I,inline:P}}static lex(e,t){return new j(t).lex(e)}static lexInline(e,t){return new j(t).inlineTokens(e)}lex(e){e=e.replace(x.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(x.tabCharGlobal," ").replace(x.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)}},B=class{options;parser;constructor(r){this.options=r||T}space(r){return""}code({text:r,lang:e,escaped:t}){let s=(e||"").match(x.notSpaceStart)?.[0],n=r.replace(x.endingNewline,"")+`\n`;return s?\'<pre><code class="language-\'+m(s)+\'">\'+(t?n:m(n,!0))+`</code></pre>\n`:"<pre><code>"+(t?n:m(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>${m(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=se(r);if(n===null)return s;r=n;let i=\'<a href="\'+r+\'"\';return e&&(i+=\' title="\'+m(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=se(r);if(n===null)return m(t);r=n;let i=`<img src="${r}" alt="${m(t)}"`;return e&&(i+=` title="${m(e)}"`),i+=">",i}text(r){return"tokens"in r&&r.tokens?this.parser.parseInline(r.tokens):"escaped"in r&&r.escaped?r.text:m(r.text)}},J=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}},w=class H{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new B,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new J}static parse(e,t){return new H(t).parse(e)}static parseInline(e,t){return new H(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}},L=class{options;block;constructor(r){this.options=r||T}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?b.lex:b.lexInline}provideParser(r=this.block){return r?w.parse:w.parseInline}},ot=class{defaults=O();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=w;Renderer=B;TextRenderer=J;Lexer=b;Tokenizer=C;Hooks=L;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 B(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 C(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 L;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];L.passThroughHooks.has(i)?n[a]=c=>{if(this.defaults.async&&L.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 b.lex(r,e??this.defaults)}parser(r,e){return w.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?b.lex:b.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?w.parse:w.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?b.lex:b.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?w.parse:w.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>"+m(t.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(t);throw t}}},S=new ot;function k(r,e){return S.parse(r,e)}k.options=k.setOptions=function(r){return S.setOptions(r),k.defaults=S.defaults,oe(k.defaults),k};k.getDefaults=O;k.defaults=T;k.use=function(...r){return S.use(...r),k.defaults=S.defaults,oe(k.defaults),k};k.walkTokens=function(r,e){return S.walkTokens(r,e)};k.parseInline=S.parseInline;k.Parser=w;k.parser=w.parse;k.Renderer=B;k.TextRenderer=J;k.Lexer=b;k.lexer=b.lex;k.Tokenizer=C;k.Hooks=L;k.parse=k;var ct=k.options,ht=k.setOptions,pt=k.use,ut=k.walkTokens,gt=k.parseInline;var kt=w.parse,dt=b.lex;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 D=new Map;self.onmessage=r=>{let e=r.data;if(typeof e!="object"||e===null)return;let{id:t,text:s,oldRaws:n,instance:i,baseVersion:a,dispose:l}=e;if(l===!0){typeof i=="string"&&D.delete(i);return}if(typeof s!="string")return;let o=typeof i=="string"?i:null,c=typeof a=="number"?a:null,p=null;if(Array.isArray(n))p=n;else if(o!==null&&c!==null){let h=D.get(o);if(h&&h.version===c)p=h.raws;else{self.postMessage({id:t,needRaws:!0});return}}try{let h=k.lexer(s),u=0;if(p){let f=Math.min(p.length,h.length);for(;u<f&&p[u]===h[u].raw;u++);}o!==null&&c!==null&&D.set(o,{version:c+1,raws:h.map(f=>f.raw)}),self.postMessage({id:t,matchLen:u,tail:h.slice(u)})}catch(h){o!==null&&D.delete(o),self.postMessage({id:t,error:String(h)})}};})();\n';
41
43
 
42
44
  // src/Markdown.ts
45
+ var now = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
43
46
  import_marked.marked.use({
44
47
  extensions: [
45
48
  {
@@ -553,6 +556,9 @@ var CodeBlock = class extends import_ui.UIComponent {
553
556
  r.roundRect(0, 0, this.width, this.height, 8);
554
557
  r.fill(this.theme.codeBgColor);
555
558
  const grid = this.ensureGrid();
559
+ const atlas = codeGlyphAtlas(r);
560
+ const atlasSource = atlas?.source ?? null;
561
+ const blit = atlas ? r.drawImageRect : void 0;
556
562
  for (let row = 0; row < grid.lines.length; row++) {
557
563
  const yBaseline = this.pad + row * this.lineH + this.lineH * 0.75;
558
564
  const segments = this.lines[row];
@@ -567,17 +573,51 @@ var CodeBlock = class extends import_ui.UIComponent {
567
573
  }
568
574
  const sourceText = this.source.slice(cell.sourceStart, cell.sourceEnd);
569
575
  if (cell.advance <= 0 || sourceText === " " || sourceText === " ") continue;
570
- r.fillText(
571
- cell.glyph,
572
- this.pad + cell.x,
573
- yBaseline,
574
- this.codeFont,
575
- segments[segmentIndex]?.color ?? this.theme.codeColor
576
- );
576
+ const color = segments[segmentIndex]?.color ?? this.theme.codeColor;
577
+ const x = this.pad + cell.x;
578
+ if (blit && atlas) {
579
+ const slot = atlas.get(this.codeFont, color, cell.glyph);
580
+ const src = atlasSource ?? atlas.source;
581
+ if (slot && src) {
582
+ blit.call(
583
+ r,
584
+ src,
585
+ slot.sx,
586
+ slot.sy,
587
+ slot.sw,
588
+ slot.sh,
589
+ x - slot.offsetX,
590
+ yBaseline - slot.offsetY,
591
+ slot.w,
592
+ slot.h
593
+ );
594
+ continue;
595
+ }
596
+ }
597
+ r.fillText(cell.glyph, x, yBaseline, this.codeFont, color);
577
598
  }
578
599
  }
579
600
  }
580
601
  };
602
+ var sharedCodeAtlas = null;
603
+ function codeGlyphAtlas(r) {
604
+ if (typeof r.drawImageRect !== "function") return void 0;
605
+ if (typeof document === "undefined") return void 0;
606
+ sharedCodeAtlas ??= new import_core.GlyphRasterAtlas({
607
+ // Match the display so a HiDPI blit stays crisp. Capped at 3 because atlas
608
+ // area grows with dpr² and a 4x display would otherwise blow the size cap
609
+ // with a few hundred glyphs.
610
+ dpr: typeof window !== "undefined" ? Math.min(window.devicePixelRatio || 1, 3) : 1,
611
+ maxSize: 2048
612
+ });
613
+ return sharedCodeAtlas;
614
+ }
615
+ function codeAtlasStats() {
616
+ return sharedCodeAtlas ? sharedCodeAtlas.stats : null;
617
+ }
618
+ function codeAtlas() {
619
+ return sharedCodeAtlas;
620
+ }
581
621
  function decodeEntities(text) {
582
622
  return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
583
623
  }
@@ -717,6 +757,40 @@ var Markdown = class extends import_ui.UIComponent {
717
757
  // with the latest accumulated text once it resolves.
718
758
  appendInFlight = false;
719
759
  appendPending = false;
760
+ /**
761
+ * Streaming counters for the DevTools inspector.
762
+ *
763
+ * Cheap enough to keep always-on (four integer increments per append) and the
764
+ * only way to see, from outside, whether incremental reuse is actually working:
765
+ * a stable-prefix ratio near 1 means the worker is matching almost everything
766
+ * and only the tail is re-lexed, while a ratio near 0 means every chunk is
767
+ * re-parsing the whole document.
768
+ */
769
+ streamStats = {
770
+ appends: 0,
771
+ workerResponses: 0,
772
+ /** Sum of `matchLen` across responses, i.e. tokens reused rather than re-lexed. */
773
+ tokensReused: 0,
774
+ /** Sum of returned tail lengths, i.e. tokens the worker had to re-lex. */
775
+ tokensRelexed: 0,
776
+ /** Total round-trip ms across worker lex requests, dispatch to callback. */
777
+ workerMs: 0,
778
+ /** Longest single worker round trip, which is what a dropped frame feels. */
779
+ workerMsMax: 0,
780
+ /**
781
+ * Source length of the stable prefix on the most recent append: the text the
782
+ * worker matched and did not re-read.
783
+ */
784
+ stablePrefixChars: 0,
785
+ /** Source length of the tail that had to be re-lexed on the most recent append. */
786
+ changedTailChars: 0,
787
+ /** Child entities kept across reconciles, either untouched or updated in place. */
788
+ entitiesReused: 0,
789
+ /** Child entities destroyed and rebuilt across reconciles. */
790
+ entitiesRebuilt: 0,
791
+ /** In-place updates via setCode/setSpans, the streaming fast path. */
792
+ inPlaceUpdates: 0
793
+ };
720
794
  // Worker request ids dispatched by *this* instance that haven't resolved yet.
721
795
  // The module-level `workerCallbacks` map holds a closure capturing `this`, so
722
796
  // destroying a Markdown mid-stream would pin the whole entity (and its subtree)
@@ -809,6 +883,130 @@ var Markdown = class extends import_ui.UIComponent {
809
883
  });
810
884
  super.destroy();
811
885
  }
886
+ /**
887
+ * Streaming and parse state — the markdown streaming inspector.
888
+ *
889
+ * Source length, chunk count, worker in-flight state, and the stable-prefix
890
+ * versus re-lexed-tail split. That last ratio is the one worth watching: it is
891
+ * how you tell incremental reuse is working from outside, and nothing else
892
+ * surfaces it. A ratio near 1 means the worker matched almost the whole prefix
893
+ * and only re-lexed the tail; near 0 means every chunk re-parses the document.
894
+ */
895
+ getDevtoolsDescriptor() {
896
+ const s = this.streamStats;
897
+ const lexed = s.tokensReused + s.tokensRelexed;
898
+ const reuseRatio = lexed > 0 ? s.tokensReused / lexed : 0;
899
+ return {
900
+ kind: "Markdown",
901
+ groups: [
902
+ {
903
+ label: "Source",
904
+ fields: [
905
+ { label: "sourceLength", value: this.rawMarkdown.length, readOnly: true },
906
+ { label: "topLevelTokens", value: this.tokens.length, readOnly: true },
907
+ { label: "childEntities", value: this.content.children.length, readOnly: true },
908
+ { label: "selectable", value: this.selectable }
909
+ ]
910
+ },
911
+ {
912
+ label: "Streaming",
913
+ fields: [
914
+ { label: "appends", value: s.appends, readOnly: true },
915
+ {
916
+ label: "workerResponses",
917
+ value: s.workerResponses,
918
+ hint: "Fewer than appends means chunks were coalesced while a request was in flight",
919
+ readOnly: true
920
+ },
921
+ {
922
+ label: "appendInFlight",
923
+ value: this.appendInFlight,
924
+ hint: "One lex request at a time; the delta protocol requires it",
925
+ readOnly: true
926
+ },
927
+ { label: "appendPending", value: this.appendPending, readOnly: true },
928
+ {
929
+ label: "workerMsAvg",
930
+ value: s.workerResponses > 0 ? Math.round(s.workerMs / s.workerResponses * 100) / 100 : 0,
931
+ hint: "Mean lex round trip, dispatch to applied",
932
+ readOnly: true
933
+ },
934
+ {
935
+ label: "workerMsMax",
936
+ value: Math.round(s.workerMsMax * 100) / 100,
937
+ hint: "Worst single round trip \u2014 this is the one a dropped frame comes from",
938
+ readOnly: true
939
+ }
940
+ ]
941
+ },
942
+ {
943
+ label: "Delta shape",
944
+ fields: [
945
+ {
946
+ label: "stablePrefixChars",
947
+ value: s.stablePrefixChars,
948
+ hint: "Source characters the worker matched and did not re-read, on the last append",
949
+ readOnly: true
950
+ },
951
+ {
952
+ label: "changedTailChars",
953
+ value: s.changedTailChars,
954
+ hint: "Source characters re-lexed on the last append. Growing with the document means O(document) per chunk",
955
+ readOnly: true
956
+ },
957
+ {
958
+ label: "entitiesReused",
959
+ value: s.entitiesReused,
960
+ hint: "Child entities kept untouched across reconciles",
961
+ readOnly: true
962
+ },
963
+ {
964
+ label: "entitiesRebuilt",
965
+ value: s.entitiesRebuilt,
966
+ hint: "Child entities destroyed and reconstructed",
967
+ readOnly: true
968
+ },
969
+ {
970
+ label: "inPlaceUpdates",
971
+ value: s.inPlaceUpdates,
972
+ hint: "setCode/setSpans on the growing last block \u2014 the streaming fast path",
973
+ readOnly: true
974
+ }
975
+ ]
976
+ },
977
+ {
978
+ label: "Incremental reuse",
979
+ fields: [
980
+ {
981
+ label: "tokensReused",
982
+ value: s.tokensReused,
983
+ hint: "Sum of matchLen: prefix tokens the worker matched and did not re-lex",
984
+ readOnly: true
985
+ },
986
+ {
987
+ label: "tokensRelexed",
988
+ value: s.tokensRelexed,
989
+ hint: "Sum of returned tail lengths: tokens the worker had to re-lex",
990
+ readOnly: true
991
+ },
992
+ {
993
+ label: "reuseRatio",
994
+ value: Math.round(reuseRatio * 1e3) / 1e3,
995
+ hint: "reused / (reused + relexed). Near 1 is healthy; near 0 means no reuse",
996
+ readOnly: true
997
+ }
998
+ ]
999
+ }
1000
+ ],
1001
+ notes: s.workerResponses === 0 && s.appends > 0 ? [
1002
+ "No worker responses yet: either the worker is unavailable and parsing ran synchronously on the main thread, or the first request is still in flight."
1003
+ ] : reuseRatio > 0 && reuseRatio < 0.5 ? [
1004
+ `Only ${Math.round(reuseRatio * 100)}% of lexed tokens were reused, so most of the document is being re-lexed per chunk. Expect O(document) work per append.`
1005
+ ] : s.changedTailChars > 0 && this.rawMarkdown.length > 0 && s.changedTailChars / this.rawMarkdown.length > 0.5 ? [
1006
+ `The last append re-lexed ${s.changedTailChars} of ${this.rawMarkdown.length} characters. A tail that grows with the document is the O(document)-per-chunk shape, even when the token reuse ratio looks healthy.`
1007
+ ] : void 0
1008
+ };
1009
+ }
812
1010
  /** Enable or disable native selection for existing and future Markdown text. */
813
1011
  setSelectable(selectable) {
814
1012
  this.selectable = selectable;
@@ -824,6 +1022,7 @@ var Markdown = class extends import_ui.UIComponent {
824
1022
  /** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
825
1023
  appendMarkdown(chunk) {
826
1024
  this.rawMarkdown += chunk;
1025
+ this.streamStats.appends++;
827
1026
  if (!markdownWorker) {
828
1027
  const newTokens = import_marked.marked.lexer(this.rawMarkdown);
829
1028
  this.updateTokens(newTokens);
@@ -854,10 +1053,21 @@ var Markdown = class extends import_ui.UIComponent {
854
1053
  const id = workerIdCounter++;
855
1054
  const oldTokensSnapshot = this.tokens;
856
1055
  const baseVersion = this.tokenVersion;
1056
+ const dispatchedAt = now();
857
1057
  this.pendingWorkerIds.add(id);
858
1058
  workerCallbacks.set(id, {
859
1059
  cb: (matchLen, tail) => {
860
1060
  this.pendingWorkerIds.delete(id);
1061
+ this.streamStats.workerResponses++;
1062
+ this.streamStats.tokensReused += matchLen;
1063
+ this.streamStats.tokensRelexed += tail.length;
1064
+ const elapsed = now() - dispatchedAt;
1065
+ this.streamStats.workerMs += elapsed;
1066
+ if (elapsed > this.streamStats.workerMsMax) this.streamStats.workerMsMax = elapsed;
1067
+ let prefixChars = 0;
1068
+ for (let i = 0; i < matchLen; i++) prefixChars += oldTokensSnapshot[i]?.raw.length ?? 0;
1069
+ this.streamStats.stablePrefixChars = prefixChars;
1070
+ this.streamStats.changedTailChars = this.rawMarkdown.length - prefixChars;
861
1071
  this.appendInFlight = false;
862
1072
  const newTokens = [...oldTokensSnapshot.slice(0, matchLen), ...tail];
863
1073
  this.updateTokens(newTokens, matchLen);
@@ -909,6 +1119,7 @@ var Markdown = class extends import_ui.UIComponent {
909
1119
  const codeToken = newTokens[matchLen];
910
1120
  if (existingEntity instanceof CodeBlock) {
911
1121
  existingEntity.setCode(codeToken.text, codeToken.lang ?? void 0);
1122
+ this.streamStats.inPlaceUpdates++;
912
1123
  matchLen++;
913
1124
  this.content.resizeLastChild(existingEntity);
914
1125
  }
@@ -926,12 +1137,17 @@ var Markdown = class extends import_ui.UIComponent {
926
1137
  spans.push({ text: pToken.text });
927
1138
  }
928
1139
  existingEntity.setSpans(spans);
1140
+ this.streamStats.inPlaceUpdates++;
929
1141
  matchLen++;
930
1142
  this.content.resizeLastChild(existingEntity);
931
1143
  }
932
1144
  }
1145
+ for (let i = 0; i < matchLen; i++) {
1146
+ if (this.producesEntity(oldTokens[i])) this.streamStats.entitiesReused++;
1147
+ }
933
1148
  for (let i = matchLen; i < oldTokens.length; i++) {
934
1149
  if (this.producesEntity(oldTokens[i])) {
1150
+ this.streamStats.entitiesRebuilt++;
935
1151
  const idx = oldTokenToChild[i];
936
1152
  if (idx < oldChildren.length) {
937
1153
  oldChildren[idx].destroy();
@@ -1225,5 +1441,7 @@ var Markdown = class extends import_ui.UIComponent {
1225
1441
  // Annotate the CommonJS export names for ESM import in node:
1226
1442
  0 && (module.exports = {
1227
1443
  CodeBlock,
1228
- Markdown
1444
+ Markdown,
1445
+ codeAtlas,
1446
+ codeAtlasStats
1229
1447
  });
package/dist/index.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  import {
3
3
  BidiResolver,
4
4
  Entity,
5
+ GlyphRasterAtlas,
5
6
  prepareContentGrid,
6
7
  SVGEntity
7
8
  } from "@vectojs/core";
@@ -18,6 +19,7 @@ import { measureText, RichText, Stack, Table, Text, Image, UIComponent } from "@
18
19
  var WORKER_SOURCE_STRING = '"use strict";(()=>{function O(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=O();function oe(r){T=r}var R={exec:()=>null};function z(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(x.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}})(),x={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:z(r=>new RegExp(`^ {0,${r}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ ][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:z(r=>new RegExp(`^ {0,${r}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:z(r=>new RegExp(`^ {0,${r}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:z(r=>new RegExp(`^ {0,${r}}#`)),htmlBeginRegex:z(r=>new RegExp(`^ {0,${r}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:z(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|$)|$)/,v=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Se=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,N=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,ce=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,he=g(ce).replace(/bull/g,N).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(ce).replace(/bull/g,N).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(),G=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,ze=/^[^\\n]+/,X=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Ae=g(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace("label",X).replace("title",/(?:"(?:\\\\"?|[^"\\\\])*"|\'[^\'\\n]*(?:\\n[^\'\\n]+)*\\n?\'|\\([^()]*\\))/).getRegex(),_e=g(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,N).getRegex(),q="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",W=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,Pe=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",W).replace("tag",q).replace("attribute",/ +[a-zA-Z:_][\\w.:-]*(?: *= *"[^"\\n]*"| *= *\'[^\'\\n]*\'| *= *[^\\s"\'=<>`]+)?/).getRegex(),pe=r=>g(G).replace("hr",v).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",q).getRegex(),Le=pe(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),ve=pe(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),Ie=g(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace("paragraph",ve).getRegex(),F={blockquote:Ie,code:$e,def:Ae,fences:Re,heading:Se,hr:v,html:Pe,lheading:he,list:_e,newline:ye,paragraph:Le,table:R,text:ze},te=g("^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)").replace("hr",v).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",q).getRegex(),Ee={...F,lheading:Te,table:te,paragraph:g(G).replace("hr",v).replace("heading"," {0,3}#{1,6}(?:\\\\s|$)").replace("|lheading","").replace("table",te).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",q).getRegex()},Ce={...F,html:g(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:"[^"]*"|\'[^\']*\'|\\\\s[^\'"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace("comment",W).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:R,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:g(G).replace("hr",v).replace("heading",` *#{1,6} *[^\n]`).replace("lheading",he).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Be=/^\\\\([!"#$%&\'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,qe=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ue=/^( {2,}|\\\\)\\n(?!\\s*$)/,Ze=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,A=/[\\p{P}\\p{S}]/u,Z=/[\\s\\p{P}\\p{S}]/u,U=/[^\\s\\p{P}\\p{S}]/u,De=g(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Z).getRegex(),ge=/(?!~)[\\p{P}\\p{S}]/u,Me=/(?!~)[\\s\\p{P}\\p{S}]/u,Qe=/(?:[^\\s\\p{P}\\p{S}]|~)/u,je=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(),ke=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,He=g(ke,"u").replace(/punct/g,A).getRegex(),Oe=g(ke,"u").replace(/punct/g,ge).getRegex(),de="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)",Ne=g(de,"gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),Ge=g(de,"gu").replace(/notPunctSpace/g,Qe).replace(/punctSpace/g,Me).replace(/punct/g,ge).getRegex(),Xe=g("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),We=g(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,A).getRegex(),Fe="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ue=g(Fe,"gu").replace(/notPunctSpace/g,U).replace(/punctSpace/g,Z).replace(/punct/g,A).getRegex(),Ve=g(/\\\\(punct)/,"gu").replace(/punct/g,A).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(W).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(),E=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,et=g(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",E).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|\'(?:\\\\\'?|[^\'\\\\])*\'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),fe=g(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",E).replace("ref",X).getRegex(),xe=g(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",X).getRegex(),tt=g("reflink|nolink(?!\\\\()","g").replace("reflink",fe).replace("nolink",xe).getRegex(),re=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V={_backpedal:R,anyPunctuation:Ve,autolink:Je,blockSkip:je,br:ue,code:qe,del:R,delLDelim:R,delRDelim:R,emStrongLDelim:He,emStrongRDelimAst:Ne,emStrongRDelimUnd:Xe,escape:Be,link:et,nolink:xe,punctuation:De,reflink:fe,reflinkSearch:tt,tag:Ye,text:Ze,url:R},rt={...V,link:g(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",E).getRegex(),reflink:g(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",E).getRegex()},Q={...V,emStrongRDelimAst:Ge,emStrongLDelim:Oe,delLDelim:We,delRDelim:Ue,url:g(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",re).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",re).getRegex()},nt={...Q,br:g(ue).replace("{2,}","*").getRegex(),text:g(Q.text).replace("\\\\b_","\\\\b_| {2,}\\\\n").replace(/\\{2,\\}/g,"*").getRegex()},I={normal:F,gfm:Ee,pedantic:Ce},P={normal:V,gfm:Q,breaks:nt,pedantic:rt},st={"&":"&amp;","<":"&lt;",">":"&gt;",\'"\':"&quot;","\'":"&#39;"},ne=r=>st[r];function m(r,e){if(e){if(x.escapeTest.test(r))return r.replace(x.escapeReplace,ne)}else if(x.escapeTestNoEncode.test(r))return r.replace(x.escapeReplaceNoEncode,ne);return r}function se(r){try{r=encodeURI(r).replace(x.percentDecode,"%")}catch{return null}return r}function ie(r,e){let t=r.replace(x.findPipe,(i,a,l)=>{let o=!1,c=a;for(;--c>=0&&l[c]==="\\\\";)o=!o;return o?"|":" |"}),s=t.split(x.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(x.slashPipe,"|");return s}function $(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 le(r){let e=r.split(`\n`),t=e.length-1;for(;t>=0&&x.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 ae(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 C=class{options;rules;lexer;constructor(r){this.options=r||T}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]:le(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=$(t,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(t=s.trim())}return{type:"heading",raw:$(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:$(e[0],`\n`)}}blockquote(r){let e=this.rules.block.blockquote.exec(r);if(e){let t=$(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 f=u,d=f.raw+`\n`+t.join(`\n`),y=this.blockquote(d);i[i.length-1]=y,s=s.substring(0,s.length-f.raw.length)+y.raw,n=n.substring(0,n.length-f.text.length)+y.text;break}else if(u?.type==="list"){let f=u,d=f.raw+`\n`+t.join(`\n`),y=this.list(d);i[i.length-1]=y,s=s.substring(0,s.length-u.raw.length)+y.raw,n=n.substring(0,n.length-f.raw.length)+y.raw,t=d.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],f=!h.trim(),d=0;if(this.options.pedantic?(d=2,p=h.trimStart()):f?d=e[1].length+1:(d=h.search(this.rules.other.nonSpaceChar),d=d>4?1:d,p=h.slice(d),d+=e[1].length),f&&this.rules.other.blankLine.test(u)&&(c+=u+`\n`,r=r.substring(u.length+1),o=!0),!o){let y=this.rules.other.nextBulletRegex(d),K=this.rules.other.hrRegex(d),Y=this.rules.other.fencesBeginRegex(d),ee=this.rules.other.headingBeginRegex(d),be=this.rules.other.htmlBeginRegex(d),we=this.rules.other.blockquoteBeginRegex(d);for(;r;){let M=r.split(`\n`,1)[0],_;if(u=M,this.options.pedantic?(u=u.replace(this.rules.other.listReplaceNesting," "),_=u):_=u.replace(this.rules.other.tabCharGlobal," "),Y.test(u)||ee.test(u)||be.test(u)||we.test(u)||y.test(u)||K.test(u))break;if(_.search(this.rules.other.nonSpaceChar)>=d||!u.trim())p+=`\n`+_.slice(d);else{if(f||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||Y.test(h)||ee.test(h)||K.test(h))break;p+=`\n`+u}f=!u.trim(),c+=M+`\n`,r=r.substring(M.length+1),h=_.slice(d)}}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=le(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:$(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=ie(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:$(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(ie(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:$(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=$(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)),ae(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 ae(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 f=h.slice(1,-1);return{type:"em",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}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}}}},b=class j{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new C,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:x,block:I.normal,inline:P.normal};this.options.pedantic?(t.block=I.pedantic,t.inline=P.pedantic):this.options.gfm&&(t.block=I.gfm,this.options.breaks?t.inline=P.breaks:t.inline=P.gfm),this.tokenizer.rules=t}static get rules(){return{block:I,inline:P}}static lex(e,t){return new j(t).lex(e)}static lexInline(e,t){return new j(t).inlineTokens(e)}lex(e){e=e.replace(x.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(x.tabCharGlobal," ").replace(x.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)}},B=class{options;parser;constructor(r){this.options=r||T}space(r){return""}code({text:r,lang:e,escaped:t}){let s=(e||"").match(x.notSpaceStart)?.[0],n=r.replace(x.endingNewline,"")+`\n`;return s?\'<pre><code class="language-\'+m(s)+\'">\'+(t?n:m(n,!0))+`</code></pre>\n`:"<pre><code>"+(t?n:m(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>${m(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=se(r);if(n===null)return s;r=n;let i=\'<a href="\'+r+\'"\';return e&&(i+=\' title="\'+m(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=se(r);if(n===null)return m(t);r=n;let i=`<img src="${r}" alt="${m(t)}"`;return e&&(i+=` title="${m(e)}"`),i+=">",i}text(r){return"tokens"in r&&r.tokens?this.parser.parseInline(r.tokens):"escaped"in r&&r.escaped?r.text:m(r.text)}},J=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}},w=class H{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new B,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new J}static parse(e,t){return new H(t).parse(e)}static parseInline(e,t){return new H(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}},L=class{options;block;constructor(r){this.options=r||T}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?b.lex:b.lexInline}provideParser(r=this.block){return r?w.parse:w.parseInline}},ot=class{defaults=O();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=w;Renderer=B;TextRenderer=J;Lexer=b;Tokenizer=C;Hooks=L;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 B(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 C(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 L;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];L.passThroughHooks.has(i)?n[a]=c=>{if(this.defaults.async&&L.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 b.lex(r,e??this.defaults)}parser(r,e){return w.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?b.lex:b.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?w.parse:w.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?b.lex:b.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?w.parse:w.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>"+m(t.message+"",!0)+"</pre>";return e?Promise.resolve(s):s}if(e)return Promise.reject(t);throw t}}},S=new ot;function k(r,e){return S.parse(r,e)}k.options=k.setOptions=function(r){return S.setOptions(r),k.defaults=S.defaults,oe(k.defaults),k};k.getDefaults=O;k.defaults=T;k.use=function(...r){return S.use(...r),k.defaults=S.defaults,oe(k.defaults),k};k.walkTokens=function(r,e){return S.walkTokens(r,e)};k.parseInline=S.parseInline;k.Parser=w;k.parser=w.parse;k.Renderer=B;k.TextRenderer=J;k.Lexer=b;k.lexer=b.lex;k.Tokenizer=C;k.Hooks=L;k.parse=k;var ct=k.options,ht=k.setOptions,pt=k.use,ut=k.walkTokens,gt=k.parseInline;var kt=w.parse,dt=b.lex;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 D=new Map;self.onmessage=r=>{let e=r.data;if(typeof e!="object"||e===null)return;let{id:t,text:s,oldRaws:n,instance:i,baseVersion:a,dispose:l}=e;if(l===!0){typeof i=="string"&&D.delete(i);return}if(typeof s!="string")return;let o=typeof i=="string"?i:null,c=typeof a=="number"?a:null,p=null;if(Array.isArray(n))p=n;else if(o!==null&&c!==null){let h=D.get(o);if(h&&h.version===c)p=h.raws;else{self.postMessage({id:t,needRaws:!0});return}}try{let h=k.lexer(s),u=0;if(p){let f=Math.min(p.length,h.length);for(;u<f&&p[u]===h[u].raw;u++);}o!==null&&c!==null&&D.set(o,{version:c+1,raws:h.map(f=>f.raw)}),self.postMessage({id:t,matchLen:u,tail:h.slice(u)})}catch(h){o!==null&&D.delete(o),self.postMessage({id:t,error:String(h)})}};})();\n';
19
20
 
20
21
  // src/Markdown.ts
22
+ var now = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
21
23
  marked.use({
22
24
  extensions: [
23
25
  {
@@ -531,6 +533,9 @@ var CodeBlock = class extends UIComponent {
531
533
  r.roundRect(0, 0, this.width, this.height, 8);
532
534
  r.fill(this.theme.codeBgColor);
533
535
  const grid = this.ensureGrid();
536
+ const atlas = codeGlyphAtlas(r);
537
+ const atlasSource = atlas?.source ?? null;
538
+ const blit = atlas ? r.drawImageRect : void 0;
534
539
  for (let row = 0; row < grid.lines.length; row++) {
535
540
  const yBaseline = this.pad + row * this.lineH + this.lineH * 0.75;
536
541
  const segments = this.lines[row];
@@ -545,17 +550,51 @@ var CodeBlock = class extends UIComponent {
545
550
  }
546
551
  const sourceText = this.source.slice(cell.sourceStart, cell.sourceEnd);
547
552
  if (cell.advance <= 0 || sourceText === " " || sourceText === " ") continue;
548
- r.fillText(
549
- cell.glyph,
550
- this.pad + cell.x,
551
- yBaseline,
552
- this.codeFont,
553
- segments[segmentIndex]?.color ?? this.theme.codeColor
554
- );
553
+ const color = segments[segmentIndex]?.color ?? this.theme.codeColor;
554
+ const x = this.pad + cell.x;
555
+ if (blit && atlas) {
556
+ const slot = atlas.get(this.codeFont, color, cell.glyph);
557
+ const src = atlasSource ?? atlas.source;
558
+ if (slot && src) {
559
+ blit.call(
560
+ r,
561
+ src,
562
+ slot.sx,
563
+ slot.sy,
564
+ slot.sw,
565
+ slot.sh,
566
+ x - slot.offsetX,
567
+ yBaseline - slot.offsetY,
568
+ slot.w,
569
+ slot.h
570
+ );
571
+ continue;
572
+ }
573
+ }
574
+ r.fillText(cell.glyph, x, yBaseline, this.codeFont, color);
555
575
  }
556
576
  }
557
577
  }
558
578
  };
579
+ var sharedCodeAtlas = null;
580
+ function codeGlyphAtlas(r) {
581
+ if (typeof r.drawImageRect !== "function") return void 0;
582
+ if (typeof document === "undefined") return void 0;
583
+ sharedCodeAtlas ??= new GlyphRasterAtlas({
584
+ // Match the display so a HiDPI blit stays crisp. Capped at 3 because atlas
585
+ // area grows with dpr² and a 4x display would otherwise blow the size cap
586
+ // with a few hundred glyphs.
587
+ dpr: typeof window !== "undefined" ? Math.min(window.devicePixelRatio || 1, 3) : 1,
588
+ maxSize: 2048
589
+ });
590
+ return sharedCodeAtlas;
591
+ }
592
+ function codeAtlasStats() {
593
+ return sharedCodeAtlas ? sharedCodeAtlas.stats : null;
594
+ }
595
+ function codeAtlas() {
596
+ return sharedCodeAtlas;
597
+ }
559
598
  function decodeEntities(text) {
560
599
  return text.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/g, "&");
561
600
  }
@@ -695,6 +734,40 @@ var Markdown = class extends UIComponent {
695
734
  // with the latest accumulated text once it resolves.
696
735
  appendInFlight = false;
697
736
  appendPending = false;
737
+ /**
738
+ * Streaming counters for the DevTools inspector.
739
+ *
740
+ * Cheap enough to keep always-on (four integer increments per append) and the
741
+ * only way to see, from outside, whether incremental reuse is actually working:
742
+ * a stable-prefix ratio near 1 means the worker is matching almost everything
743
+ * and only the tail is re-lexed, while a ratio near 0 means every chunk is
744
+ * re-parsing the whole document.
745
+ */
746
+ streamStats = {
747
+ appends: 0,
748
+ workerResponses: 0,
749
+ /** Sum of `matchLen` across responses, i.e. tokens reused rather than re-lexed. */
750
+ tokensReused: 0,
751
+ /** Sum of returned tail lengths, i.e. tokens the worker had to re-lex. */
752
+ tokensRelexed: 0,
753
+ /** Total round-trip ms across worker lex requests, dispatch to callback. */
754
+ workerMs: 0,
755
+ /** Longest single worker round trip, which is what a dropped frame feels. */
756
+ workerMsMax: 0,
757
+ /**
758
+ * Source length of the stable prefix on the most recent append: the text the
759
+ * worker matched and did not re-read.
760
+ */
761
+ stablePrefixChars: 0,
762
+ /** Source length of the tail that had to be re-lexed on the most recent append. */
763
+ changedTailChars: 0,
764
+ /** Child entities kept across reconciles, either untouched or updated in place. */
765
+ entitiesReused: 0,
766
+ /** Child entities destroyed and rebuilt across reconciles. */
767
+ entitiesRebuilt: 0,
768
+ /** In-place updates via setCode/setSpans, the streaming fast path. */
769
+ inPlaceUpdates: 0
770
+ };
698
771
  // Worker request ids dispatched by *this* instance that haven't resolved yet.
699
772
  // The module-level `workerCallbacks` map holds a closure capturing `this`, so
700
773
  // destroying a Markdown mid-stream would pin the whole entity (and its subtree)
@@ -787,6 +860,130 @@ var Markdown = class extends UIComponent {
787
860
  });
788
861
  super.destroy();
789
862
  }
863
+ /**
864
+ * Streaming and parse state — the markdown streaming inspector.
865
+ *
866
+ * Source length, chunk count, worker in-flight state, and the stable-prefix
867
+ * versus re-lexed-tail split. That last ratio is the one worth watching: it is
868
+ * how you tell incremental reuse is working from outside, and nothing else
869
+ * surfaces it. A ratio near 1 means the worker matched almost the whole prefix
870
+ * and only re-lexed the tail; near 0 means every chunk re-parses the document.
871
+ */
872
+ getDevtoolsDescriptor() {
873
+ const s = this.streamStats;
874
+ const lexed = s.tokensReused + s.tokensRelexed;
875
+ const reuseRatio = lexed > 0 ? s.tokensReused / lexed : 0;
876
+ return {
877
+ kind: "Markdown",
878
+ groups: [
879
+ {
880
+ label: "Source",
881
+ fields: [
882
+ { label: "sourceLength", value: this.rawMarkdown.length, readOnly: true },
883
+ { label: "topLevelTokens", value: this.tokens.length, readOnly: true },
884
+ { label: "childEntities", value: this.content.children.length, readOnly: true },
885
+ { label: "selectable", value: this.selectable }
886
+ ]
887
+ },
888
+ {
889
+ label: "Streaming",
890
+ fields: [
891
+ { label: "appends", value: s.appends, readOnly: true },
892
+ {
893
+ label: "workerResponses",
894
+ value: s.workerResponses,
895
+ hint: "Fewer than appends means chunks were coalesced while a request was in flight",
896
+ readOnly: true
897
+ },
898
+ {
899
+ label: "appendInFlight",
900
+ value: this.appendInFlight,
901
+ hint: "One lex request at a time; the delta protocol requires it",
902
+ readOnly: true
903
+ },
904
+ { label: "appendPending", value: this.appendPending, readOnly: true },
905
+ {
906
+ label: "workerMsAvg",
907
+ value: s.workerResponses > 0 ? Math.round(s.workerMs / s.workerResponses * 100) / 100 : 0,
908
+ hint: "Mean lex round trip, dispatch to applied",
909
+ readOnly: true
910
+ },
911
+ {
912
+ label: "workerMsMax",
913
+ value: Math.round(s.workerMsMax * 100) / 100,
914
+ hint: "Worst single round trip \u2014 this is the one a dropped frame comes from",
915
+ readOnly: true
916
+ }
917
+ ]
918
+ },
919
+ {
920
+ label: "Delta shape",
921
+ fields: [
922
+ {
923
+ label: "stablePrefixChars",
924
+ value: s.stablePrefixChars,
925
+ hint: "Source characters the worker matched and did not re-read, on the last append",
926
+ readOnly: true
927
+ },
928
+ {
929
+ label: "changedTailChars",
930
+ value: s.changedTailChars,
931
+ hint: "Source characters re-lexed on the last append. Growing with the document means O(document) per chunk",
932
+ readOnly: true
933
+ },
934
+ {
935
+ label: "entitiesReused",
936
+ value: s.entitiesReused,
937
+ hint: "Child entities kept untouched across reconciles",
938
+ readOnly: true
939
+ },
940
+ {
941
+ label: "entitiesRebuilt",
942
+ value: s.entitiesRebuilt,
943
+ hint: "Child entities destroyed and reconstructed",
944
+ readOnly: true
945
+ },
946
+ {
947
+ label: "inPlaceUpdates",
948
+ value: s.inPlaceUpdates,
949
+ hint: "setCode/setSpans on the growing last block \u2014 the streaming fast path",
950
+ readOnly: true
951
+ }
952
+ ]
953
+ },
954
+ {
955
+ label: "Incremental reuse",
956
+ fields: [
957
+ {
958
+ label: "tokensReused",
959
+ value: s.tokensReused,
960
+ hint: "Sum of matchLen: prefix tokens the worker matched and did not re-lex",
961
+ readOnly: true
962
+ },
963
+ {
964
+ label: "tokensRelexed",
965
+ value: s.tokensRelexed,
966
+ hint: "Sum of returned tail lengths: tokens the worker had to re-lex",
967
+ readOnly: true
968
+ },
969
+ {
970
+ label: "reuseRatio",
971
+ value: Math.round(reuseRatio * 1e3) / 1e3,
972
+ hint: "reused / (reused + relexed). Near 1 is healthy; near 0 means no reuse",
973
+ readOnly: true
974
+ }
975
+ ]
976
+ }
977
+ ],
978
+ notes: s.workerResponses === 0 && s.appends > 0 ? [
979
+ "No worker responses yet: either the worker is unavailable and parsing ran synchronously on the main thread, or the first request is still in flight."
980
+ ] : reuseRatio > 0 && reuseRatio < 0.5 ? [
981
+ `Only ${Math.round(reuseRatio * 100)}% of lexed tokens were reused, so most of the document is being re-lexed per chunk. Expect O(document) work per append.`
982
+ ] : s.changedTailChars > 0 && this.rawMarkdown.length > 0 && s.changedTailChars / this.rawMarkdown.length > 0.5 ? [
983
+ `The last append re-lexed ${s.changedTailChars} of ${this.rawMarkdown.length} characters. A tail that grows with the document is the O(document)-per-chunk shape, even when the token reuse ratio looks healthy.`
984
+ ] : void 0
985
+ };
986
+ }
790
987
  /** Enable or disable native selection for existing and future Markdown text. */
791
988
  setSelectable(selectable) {
792
989
  this.selectable = selectable;
@@ -802,6 +999,7 @@ var Markdown = class extends UIComponent {
802
999
  /** Append a markdown chunk incrementally. Reuses unchanged prefix entities. */
803
1000
  appendMarkdown(chunk) {
804
1001
  this.rawMarkdown += chunk;
1002
+ this.streamStats.appends++;
805
1003
  if (!markdownWorker) {
806
1004
  const newTokens = marked.lexer(this.rawMarkdown);
807
1005
  this.updateTokens(newTokens);
@@ -832,10 +1030,21 @@ var Markdown = class extends UIComponent {
832
1030
  const id = workerIdCounter++;
833
1031
  const oldTokensSnapshot = this.tokens;
834
1032
  const baseVersion = this.tokenVersion;
1033
+ const dispatchedAt = now();
835
1034
  this.pendingWorkerIds.add(id);
836
1035
  workerCallbacks.set(id, {
837
1036
  cb: (matchLen, tail) => {
838
1037
  this.pendingWorkerIds.delete(id);
1038
+ this.streamStats.workerResponses++;
1039
+ this.streamStats.tokensReused += matchLen;
1040
+ this.streamStats.tokensRelexed += tail.length;
1041
+ const elapsed = now() - dispatchedAt;
1042
+ this.streamStats.workerMs += elapsed;
1043
+ if (elapsed > this.streamStats.workerMsMax) this.streamStats.workerMsMax = elapsed;
1044
+ let prefixChars = 0;
1045
+ for (let i = 0; i < matchLen; i++) prefixChars += oldTokensSnapshot[i]?.raw.length ?? 0;
1046
+ this.streamStats.stablePrefixChars = prefixChars;
1047
+ this.streamStats.changedTailChars = this.rawMarkdown.length - prefixChars;
839
1048
  this.appendInFlight = false;
840
1049
  const newTokens = [...oldTokensSnapshot.slice(0, matchLen), ...tail];
841
1050
  this.updateTokens(newTokens, matchLen);
@@ -887,6 +1096,7 @@ var Markdown = class extends UIComponent {
887
1096
  const codeToken = newTokens[matchLen];
888
1097
  if (existingEntity instanceof CodeBlock) {
889
1098
  existingEntity.setCode(codeToken.text, codeToken.lang ?? void 0);
1099
+ this.streamStats.inPlaceUpdates++;
890
1100
  matchLen++;
891
1101
  this.content.resizeLastChild(existingEntity);
892
1102
  }
@@ -904,12 +1114,17 @@ var Markdown = class extends UIComponent {
904
1114
  spans.push({ text: pToken.text });
905
1115
  }
906
1116
  existingEntity.setSpans(spans);
1117
+ this.streamStats.inPlaceUpdates++;
907
1118
  matchLen++;
908
1119
  this.content.resizeLastChild(existingEntity);
909
1120
  }
910
1121
  }
1122
+ for (let i = 0; i < matchLen; i++) {
1123
+ if (this.producesEntity(oldTokens[i])) this.streamStats.entitiesReused++;
1124
+ }
911
1125
  for (let i = matchLen; i < oldTokens.length; i++) {
912
1126
  if (this.producesEntity(oldTokens[i])) {
1127
+ this.streamStats.entitiesRebuilt++;
913
1128
  const idx = oldTokenToChild[i];
914
1129
  if (idx < oldChildren.length) {
915
1130
  oldChildren[idx].destroy();
@@ -1202,5 +1417,7 @@ var Markdown = class extends UIComponent {
1202
1417
  };
1203
1418
  export {
1204
1419
  CodeBlock,
1205
- Markdown
1420
+ Markdown,
1421
+ codeAtlas,
1422
+ codeAtlasStats
1206
1423
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vectojs/markdown",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },