@@ -466,9 +466,32 @@ const nolink = edit(/^!?\[(ref)\](?:\[\])?/)
466466 . replace ( 'ref' , _blockLabel )
467467 . getRegex ( ) ;
468468
469+ // `reflink` and `nolink` are anchored, so the tokenizer tries each of them at a
470+ // single position. `reflinkSearch` drops the anchors and runs with the global
471+ // flag, which makes every '[' in the source a start position. A label crosses a
472+ // bracket only by escaping it, and nothing caps how often it does, so a
473+ // candidate that can never match still scans to the end of the source and the
474+ // whole pass costs O(n^2).
475+ //
476+ // The labels below bound that scan. `_boundedInlineLabel` limits how many
477+ // escapes, code spans and nested brackets a link text may hold, leaving runs of
478+ // ordinary characters unbounded so link text of any length is still found.
479+ // `_boundedBlockLabel` limits the label itself to 999 items, which is every
480+ // label CommonMark allows: "A link label can have at most 999 characters
481+ // inside the square brackets."
482+ const _boundedBlockLabel = / (? ! \s * \] ) (?: \\ [ \s \S ] | [ ^ \[ \] \\ ] ) { 1 , 999 } / ;
483+ const _boundedInlineLabel = edit ( / (?: [ ^ \[ \] \\ ` ] * (?: \[ (?: b r a c k e t s | \\ [ \s \S ] | [ ^ \[ \] \\ ] ) * \] | \\ [ \s \S ] | ` + (? ! ` ) [ ^ ` ] * ?` + (? ! ` ) | ` ` + (? = \] ) ) ) { 0 , 999 } ?[ ^ \[ \] \\ ` ] * ?/ )
484+ . replace ( 'brackets' , _inlineLabelBrackets )
485+ . getRegex ( ) ;
486+
469487const reflinkSearch = edit ( 'reflink|nolink(?!\\()' , 'g' )
470- . replace ( 'reflink' , reflink )
471- . replace ( 'nolink' , nolink )
488+ . replace ( 'reflink' , edit ( / ^ ! ? \[ ( l a b e l ) \] \[ ( r e f ) \] / )
489+ . replace ( 'label' , _boundedInlineLabel )
490+ . replace ( 'ref' , _boundedBlockLabel )
491+ . getRegex ( ) )
492+ . replace ( 'nolink' , edit ( / ^ ! ? \[ ( r e f ) \] (?: \[ \] ) ? / )
493+ . replace ( 'ref' , _boundedBlockLabel )
494+ . getRegex ( ) )
472495 . getRegex ( ) ;
473496
474497const _caseInsensitiveProtocol = / [ h H ] [ t T ] [ t T ] [ p P ] [ s S ] ? | [ f F ] [ t T ] [ p P ] / ;
0 commit comments