@@ -104,13 +104,13 @@ export function compileTemplateToString(
104104export type Token = {
105105 type : "text" | "code" | "expr" ;
106106 contents : string ;
107- loc : {
108- start : number ;
109- end : number ;
110- } ;
111107} ;
112108
113109export function tokenize ( template : string ) : Token [ ] {
110+ if ( ! template ) {
111+ return [ ] ;
112+ }
113+
114114 // convert <script server> ... </script> to <?js ... ?>
115115 template = template . replace (
116116 / < s c r i p t \s + s e r v e r \s * > ( [ \s \S ] * ?) < \/ s c r i p t > / gi,
@@ -120,30 +120,32 @@ export function tokenize(template: string): Token[] {
120120 const tokens : Token [ ] = [ ] ;
121121 const re = / < \? (?: j s ) ? (?< equals > = ) ? (?< value > [ \s \S ] * ?) \? > / g;
122122 let cursor = 0 ;
123- let m ;
124- while ( ( m = re . exec ( template ) ) ) {
125- const { equals, value } = m . groups || { } ;
126- // Literal chunk before the tag
127- const prev = template . slice ( cursor , m . index ) ;
128- const loc = { start : cursor , end : m . index } ;
129- if ( prev ) {
130- tokens . push ( { type : "text" , contents : prev , loc } ) ;
123+ let match ;
124+ while ( ( match = re . exec ( template ) ) ) {
125+ const { equals, value } = match . groups || { } ;
126+ const matchStart = match . index ;
127+ const matchEnd = matchStart + match [ 0 ] . length ;
128+ if ( matchStart > cursor ) {
129+ const textContent = template . slice ( cursor , matchStart ) ;
130+ if ( textContent ) {
131+ tokens . push ( { type : "text" , contents : textContent } ) ;
132+ }
131133 }
132134 if ( equals ) {
133- tokens . push ( { type : "expr" , contents : value ! , loc } ) ;
135+ // Expression tag: <?= ... ?>
136+ tokens . push ( { type : "expr" , contents : value || "" } ) ;
134137 } else {
135- tokens . push ( { type : "code" , contents : value ! , loc } ) ;
138+ // Code tag: <? ... ?> or <?js ... ?>
139+ tokens . push ( { type : "code" , contents : value || "" } ) ;
136140 }
137- cursor = m . index + m [ 0 ] . length ;
141+ cursor = matchEnd ;
138142 }
139143
140- const tail = template . slice ( cursor ) ;
141- if ( tail ) {
142- tokens . push ( {
143- type : "text" ,
144- contents : tail ,
145- loc : { start : cursor , end : template . length } ,
146- } ) ;
144+ if ( cursor < template . length ) {
145+ const remainingText = template . slice ( cursor ) ;
146+ if ( remainingText ) {
147+ tokens . push ( { type : "text" , contents : remainingText } ) ;
148+ }
147149 }
148150
149151 return tokens ;
0 commit comments