@@ -44,11 +44,16 @@ export const parser = (html: string, options: Options = {}): Node[] => {
44
44
const locationTracker = new LocationTracker ( html ) ;
45
45
const bufArray : Node [ ] = [ ] ;
46
46
const results : Node [ ] = [ ] ;
47
+ let lastIndices : [ number , number ] ;
47
48
48
- function bufferArrayLast ( ) : Node {
49
+ function bufferArrayLast ( ) : Node | undefined {
49
50
return bufArray [ bufArray . length - 1 ] ;
50
51
}
51
52
53
+ function resultsLast ( ) : Node | undefined {
54
+ return results [ results . length - 1 ] ;
55
+ }
56
+
52
57
function isDirective ( directive : Directive , tag : string ) : boolean {
53
58
if ( directive . name instanceof RegExp ) {
54
59
const regex = new RegExp ( directive . name . source , 'i' ) ;
@@ -122,10 +127,20 @@ export const parser = (html: string, options: Options = {}): Node[] => {
122
127
}
123
128
124
129
function onopentag ( tag : string , attrs : Attributes ) {
125
- const start = locationTracker . getPosition ( parser . startIndex ) ;
126
130
const buf : NodeTag = { tag } ;
127
131
128
132
if ( options . sourceLocations ) {
133
+ if ( lastIndices ?. [ 0 ] === parser . startIndex && lastIndices ?. [ 1 ] === parser . endIndex ) {
134
+ // The last closing tag was inferred, so we need to update its end location
135
+ const last = bufferArrayLast ( ) || resultsLast ( ) ;
136
+
137
+ if ( typeof last === 'object' && Array . isArray ( last . content ) && last . location ) {
138
+ last . location . end = locationTracker . getPosition ( parser . startIndex - 1 )
139
+ }
140
+ }
141
+
142
+ const start = locationTracker . getPosition ( parser . startIndex ) ;
143
+
129
144
buf . location = {
130
145
start,
131
146
end : start
@@ -142,8 +157,9 @@ export const parser = (html: string, options: Options = {}): Node[] => {
142
157
function onclosetag ( ) {
143
158
const buf : Node | undefined = bufArray . pop ( ) ;
144
159
145
- if ( buf && typeof buf === 'object' && buf . location && parser . endIndex !== null ) {
146
- buf . location . end = locationTracker . getPosition ( ( ! parser . tagname || parser . tagname === buf . tag ) ? parser . endIndex : parser . startIndex - 1 ) ;
160
+ if ( buf && typeof buf === 'object' && buf . location && buf . location . end === buf . location . start && parser . endIndex !== null ) {
161
+ lastIndices = [ parser . startIndex , parser . endIndex ] ;
162
+ buf . location . end = locationTracker . getPosition ( parser . endIndex ) ;
147
163
}
148
164
149
165
if ( buf ) {
@@ -167,7 +183,7 @@ export const parser = (html: string, options: Options = {}): Node[] => {
167
183
}
168
184
169
185
function ontext ( text : string ) {
170
- const last : Node = bufferArrayLast ( ) ;
186
+ const last = bufferArrayLast ( ) ;
171
187
172
188
if ( last === undefined ) {
173
189
results . push ( text ) ;
0 commit comments