1212 * @typedef {import('hast-util-is-element').Test } Test
1313 * @typedef {import('unist-util-visit-parents').VisitorResult } VisitorResult
1414 *
15+ * @typedef RegExpMatchObject
16+ * @property {number } index
17+ * @property {string } input
18+ * @property {[Root, ...Array<Element>, Text] } stack
19+ *
1520 * @typedef {string|RegExp } Find
1621 * @typedef {string|ReplaceFunction } Replace
1722 *
@@ -97,16 +102,17 @@ export function findAndReplace(tree, find, replace, options) {
97102 }
98103
99104 if ( grandparent ) {
100- return handler ( node , grandparent )
105+ return handler ( node , parents )
101106 }
102107 }
103108
104109 /**
105110 * @param {Text } node
106- * @param {Parent } parent
111+ * @param {Array<Root|Element> } parents
107112 * @returns {VisitorResult }
108113 */
109- function handler ( node , parent ) {
114+ function handler ( node , parents ) {
115+ const parent = parents [ parents . length - 1 ]
110116 const find = pairs [ pairIndex ] [ 0 ]
111117 const replace = pairs [ pairIndex ] [ 1 ]
112118 let start = 0
@@ -122,7 +128,14 @@ export function findAndReplace(tree, find, replace, options) {
122128
123129 while ( match ) {
124130 position = match . index
125- let value = replace ( ...match , { index : match . index , input : match . input } )
131+ /** @type {RegExpMatchObject } */
132+ const matchObject = {
133+ index : match . index ,
134+ input : match . input ,
135+ // @ts -expect-error: stack is fine.
136+ stack : [ ...parents , node ]
137+ }
138+ let value = replace ( ...match , matchObject )
126139
127140 if ( typeof value === 'string' ) {
128141 value = value . length > 0 ? { type : 'text' , value} : undefined
0 commit comments